Database constraint over multiple tables - sql

Say I have the following tables:
CREATE TABLE [Weeks]
(
[Id] INT NOT NULL IDENTITY,
CONSTRAINT [PK_Weeks] PRIMARY KEY ([Id])
);
CREATE TABLE [Days]
(
[Id] INT NOT NULL IDENTITY,
[WeekId] INT NULL,
CONSTRAINT [PK_Days] PRIMARY KEY ([Id]),
CONSTRAINT [FK_Days_Weeks_WeekId]
FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id])
);
CREATE TABLE [ReplacedDayInWeek]
(
[Id] INT NOT NULL IDENTITY,
[WeekId] INT NOT NULL,
[DayId] INT NOT NULL,
[ReplacedDayId] INT NOT NULL,
CONSTRAINT [PK_ReplacedDayInWeek] PRIMARY KEY ([Id]),
CONSTRAINT [FK_ReplacedDayInWeek_Days_DayId]
FOREIGN KEY ([DayId]) REFERENCES [Days] ([Id]),
CONSTRAINT [FK_ReplacedDayInWeek_Weeks_WeekId]
FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id]),
CONSTRAINT [FK_ReplacedDayInWeek_Weeks_ReplacedWeekId]
FOREIGN KEY ([ReplacedWeekId]) REFERENCES [Weeks] ([Id])
);
The table ReplacedDayInWeek contains a day in a specific week that's replaced by another day.
How can I create a SQL constraint (or perhaps another SQL based solution) that makes sure I can only insert rows into DayInWeek with a DayId that's part of the same week as WeekId?
I'm looking for a solution with the least amount of changes to the source database. I'd prefer an additional table or table changes above stored procedures.

This data structure makes no sense to me. You have the mapping between days and weeks in two tables.
You should really only be storing the week in one table and looking it up in the other.
That said, you can do what you want using an additional constraint on day/week between the two tables:
CREATE TABLE [Days]
(
[Id] INT NOT NULL IDENTITY,
[WeekId] INT NULL,
CONSTRAINT [PK_Days] PRIMARY KEY ([Id]),
CONSTRAINT [FK_Days_Weeks_WeekId]
FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id]),
CONSTRAINT UNQ_Days_WeekId_Id UNIQUE (WeekId, Id)
);
CREATE TABLE [DaysInWeek]
(
[Id] INT NOT NULL IDENTITY,
[WeekId] INT NOT NULL,
[DayId] INT NOT NULL,
CONSTRAINT [PK_DaysInWeek] PRIMARY KEY([Id]),
CONSTRAINT [FK_DaysInWeek_Days_WeekId_DayId]
FOREIGN KEY (WeekId, DayId) REFERENCES Days(WeekId, Id),
CONSTRAINT [FK_DaysInWeek_Weeks_WeekId]
FOREIGN KEY ([WeekId]) REFERENCES [Weeks] ([Id])
);

Related

Add constraints for a foreign key that references multipleprimary keys from different tables in SQL Plus?

I'm a beginner learning SQL and am having trouble implementing this concept.
Suppose you create the following three tables:
CREATE TABLE dogOwner(
ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk1 PRIMARY KEY,
ownerName VARCHAR(10)
);
CREATE TABLE catOwner(
ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk2 PRIMARY KEY,
ownerName VARCHAR(10)
);
CREATE TABLE petsAdopted(
petNo VARCHAR(8) CONSTRAINT petNo_pk PRIMARY KEY,
ownerNo VARCHAR(8) CONSTRAINT ownerNo_fk1 REFERENCES dogOwner(ownerNo)
CONSTRAINT ownerNo_fk2 REFERENCES catOwner(ownerNo)
);
How do you properly create constraints for the foreign key ownerNo, which references ownerNo from two other tables?
You can't. You could have 2 columns in petsAdopted: dogOwnerNo and catOwnerNo and 2 foreign keys. But the table design doesn't seem to make sense: surely a pet either is a dog or a cat (or something else) regardless of who owns it?
Here is an alternative design:
CREATE TABLE owner(
ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk2 PRIMARY KEY,
ownerName VARCHAR(10)
);
CREATE TABLE petsAdopted(
petNo VARCHAR(8) CONSTRAINT petNo_pk PRIMARY KEY,
petType VARCHAR2(10) NOT NULL CONSTRAINT petTypeChk (CHECK petType in ('CAT','DOG'))
ownerNo VARCHAR(8) CONSTRAINT ownerNo_fk REFERENCES owner(ownerNo)
);
This only address syntax part of your answer which You have got lot of syntax error, but this will not work, Please rethink your design.
CREATE TABLE dogOwner(
ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk1 PRIMARY KEY,
ownerName VARCHAR(10)
);
CREATE TABLE catOwner(
ownerNo VARCHAR(8),
ownerName VARCHAR(10),
CONSTRAINT ownerNo_pk2 PRIMARY KEY (ownerNo),
CONSTRAINT ownerNo_fk1 FOREIGN KEY (ownerNo) REFERENCES dogOwner(ownerNo)
);
CREATE TABLE petsAdopted(
petNo VARCHAR(8) ,
ownerNo VARCHAR(8),
CONSTRAINT petNo_pk PRIMARY KEY (petNo),
CONSTRAINT ownerNo_fk_pet1 FOREIGN KEY (ownerNo) REFERENCES dogOwner(ownerNo),
CONSTRAINT ownerNo_fk_pet2 FOREIGN KEY (ownerNo) REFERENCES catOwner(ownerNo)
);

Add constraint to compare two attributes of different tables?

Here are my tables. I need to check that the 'program' attribute referenced in StudentsBranch with the table Students and the table Branches is the same. How can I do it?
CREATE TABLE Programmes (
name VARCHAR(200) UNIQUE NOT NULL,
CONSTRAINT pk_Programmes PRIMARY KEY (name)
);
CREATE TABLE Students (
id NUMERIC(10,0) UNIQUE NOT NULL,
program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Students PRIMARY KEY (idnr),
FOREIGN KEY (program) REFERENCES Programmes(name)
);
CREATE TABLE Branches (
name VARCHAR(200) UNIQUE NOT NULL,
program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Branches PRIMARY KEY (name, program),
FOREIGN KEY (program) REFERENCES Programmes(name)
);
CREATE TABLE StudentsBranch (
student NUMERIC(10,0) NOT NULL,
program VARCHAR(200) NOT NULL,
branch VARCHAR(200) NOT NULL,
CONSTRAINT pk_StudentsBranch PRIMARY KEY (student),
/* Below how the foreign keys I think should be */
FOREIGN KEY (student, program) REFERENCES Students(idnr, program),
FOREIGN KEY (branch, program) REFERENCES Branches(name, program)
/* I need to add a constraint to verify that the 'program' in Students
* and the 'program' in Branches are equivalent. How?
*/
);
You can't write that constraint with that existing database model you have now.
The only way I see you could do it, is by changing the primary key of Students to (id, program):
CREATE TABLE Students (
id NUMERIC(10,0) UNIQUE NOT NULL,
program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Students PRIMARY KEY (id, program),
FOREIGN KEY (program) REFERENCES Programmes(name)
);
Then the table StudentsBranch could naturally enforce both FKs with using the single column program, as in:
CREATE TABLE StudentsBranch (
student NUMERIC(10,0) NOT NULL,
program VARCHAR(200) NOT NULL,
branch VARCHAR(200) NOT NULL,
CONSTRAINT pk_StudentsBranch PRIMARY KEY (student),
FOREIGN KEY (student, program) REFERENCES Students (id, program),
FOREIGN KEY (branch, program) REFERENCES Branches (name, program)
);
It is always a good idea to have an numeric column of primary key and have primary key for every table.
Once you have primary key for every table you can referece primary key of a specific table and refere it as foerign key.
CREATE TABLE Programmes (
ID INT,
name VARCHAR(200) UNIQUE NOT NULL,
CONSTRAINT pk_Programmes PRIMARY KEY (ID)
);
CREATE TABLE Students(
id INT,
ProgrammID INT NOT NULL,
CONSTRAINT pk_Students PRIMARY KEY (ID),
FOREIGN KEY (ProgrammID) REFERENCES Programmes(ID)
);
CREATE TABLE Branches (
BranchID INT,
ProgrammID INT NOT NULL,
name VARCHAR(200) UNIQUE NOT NULL,
--program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Branches PRIMARY KEY (BranchID, ProgrammID),
FOREIGN KEY (ProgrammID) REFERENCES Programmes(ID)
);
CREATE TABLE StudentsBranch (
StudentsBranchID INT,
studentID INT NOT NULL,
ProgrammID INT NOT NULL,
BranchID INT NOT NULL,
CONSTRAINT pk_StudentsBranch PRIMARY KEY (StudentsBranchID),
FOREIGN KEY (ProgrammID) REFERENCES Programmes(id),
FOREIGN KEY (studentID) REFERENCES Students(id),
FOREIGN KEY (BranchID, ProgrammID) REFERENCES Branches(BranchID, ProgrammID)
);

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);

Error There are no primary or candidate keys in the referenced table

I'm getting this error when trying to create a table with foreign key:
There are no primary or candidate keys in the referenced table 'TeamToPlayers' that match the referencing column list in the foreign key 'FKey2'.
I don't understand why, there is a primary key in the table TeamToPlayers.
Here are the queries:
create table TeamToPlayers
(TeamName varchar(50) NOT NULL,
PlayerName varchar(50) NOT NULL,
primary key(TeamName,PlayerName),
CONSTRAINT FKey FOREIGN KEY (TeamName) REFERENCES Teams(TeamName)
)
create table Players
(PlayerName varchar(50) NOT NULL,
primary key(PlayerName),
CONSTRAINT FKey2 FOREIGN KEY (PlayerName) REFERENCES TeamToPlayers(PlayerName)
);
Table TeamToPlayers primary key consists of two fields - you must reference both as otherwise it's not a key. I think you may have your key the wrong way round - it should be on TeamToPlayers and referencing Players like so:
create table TeamToPlayers
(
TeamName varchar(50) NOT NULL,
PlayerName varchar(50) NOT NULL,
primary key(TeamName,PlayerName),
CONSTRAINT FKey FOREIGN KEY (TeamName) REFERENCES Teams(TeamName),
CONSTRAINT FKey2 FOREIGN KEY (PlayerName) REFERENCES Players(PlayerName)
)
create table Players
(PlayerName varchar(50) NOT NULL,
primary key(PlayerName),
);

Error Defining Foreign Key

I have the following two database tables defined:
CREATE TABLE [dbo].[Classrooms] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[ClassroomName] VARCHAR (30) NOT NULL,
CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [FK_Classrooms_SystemAccount] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [dbo].[SystemAccounts] ([ID])
);
CREATE TABLE [dbo].[Students] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[Classroom_ID] INT NULL,
[PhotoID] INT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (40) NOT NULL,
[NewsTemplate] TINYINT NOT NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Students_Classrooms] FOREIGN KEY ([Classroom_ID]) REFERENCES [dbo].[Classrooms] ([ID]),
CONSTRAINT [FK_Students_SystemAccounts] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [dbo].[SystemAccounts] ([ID])
);
Data model details:
Students belong to zero or one classroom via Classroom_ID FK
Students belong to one System Account via SystemAccount_ID FK
Classrooms belong to one System Account via SystemAccount_ID FK (implying a system account can have zero or more Classrooms)
What I'm attempting to do is enforce when students are added to a classroom (by setting the Classroom_ID key in the Students table) that the classroom belongs to the same system account as the student. I could easily enforce this at the business logic layer but then I'd be requiring every programmer to remember to do this. So ideally, I'd be able to do this at the data layer as a constraint.
I tried adding a FK constraint to the Students table:
CONSTRAINT [FK_Students_ToTable] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [Classrooms]([SystemAccount_ID])
Which results in the following error compliments of SQL Server:
Update cannot proceed due to validation errors.
Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[Classrooms]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
I've tried a few different things but my SQL mojo isn't powerful enough to hack past this one. Any help would be greatly appreciated.
Add a UNIQUE constraint on the combination of the two columns in Classrooms:
CREATE TABLE [dbo].[Classrooms] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[ClassroomName] VARCHAR (30) NOT NULL,
CONSTRAINT [PK_Table]
PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [FK_Classrooms_SystemAccount]
FOREIGN KEY ([SystemAccount_ID])
REFERENCES [dbo].[SystemAccounts] ([ID]),
CONSTRAINT [UQ_Classrooms_ID_SystemAccount_ID]
UNIQUE ([SystemAccount_ID], [ID])
);
Then, in the Students table, combine the two FOREIGN KEY constraints into one, or in your case (because Classroom_ID isnullable), change the FK to Classroom to use the combination of the two columns:
CREATE TABLE [dbo].[Students] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[Classroom_ID] INT NULL,
[PhotoID] INT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (40) NOT NULL,
[NewsTemplate] TINYINT NOT NULL,
CONSTRAINT [PK_Students]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Students_Classrooms]
FOREIGN KEY ([SystemAccount_ID], [Classroom_ID])
REFERENCES [dbo].[Classrooms] ([SystemAccount_ID], [ID]),
CONSTRAINT [FK_Students_SystemAccounts] -- this wouldn't be needed if
FOREIGN KEY ([SystemAccount_ID]) -- Classrooms_ID was NOT NULL
REFERENCES [dbo].[SystemAccounts] ([ID])
);