SQL Relation MORE on MORE - sql-server

I have a question about this relation betweed SpelerTeam and Toernooi, i get a error, can someone help me with it all the other relations do work:
Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
keys in the referenced table 'SpelerTeam' that match the referencing
column list in the foreign key 'FK__Toernooi__team__1A14E395'. Msg
1750, Level 16, State 0, Line 2 Could not create constraint. See
previous errors.
CREATE TABLE dbo.LoginGegevens
(
Username varchar(25) NOT NULL,
Wachtwoord varchar(25) NOT NULL,
LoginDatum date NOT NULL,
)
CREATE TABLE dbo.NawGegevensKind
(
KindSpeler varchar(25) NOT NULL,
NawKind varchar(50) NOT NULL,
)
CREATE TABLE dbo.NawGegevensProfspeler
(
Profspeler varchar(25) NOT NULL,
NawProfspeler varchar(50) NOT NULL,
)
CREATE TABLE dbo.SpelerTeam
(
Team int NOT NULL,
Kindspeler varchar(25) NOT NULL,
Profspeler varchar(25) NOT NULL,
)
CREATE TABLE dbo.Toernooi
(
team int NOT NULL,
score int NOT NULL,
games int NOT NULL,
rondes int NOT NULL,
)
-- primary keys
ALTER TABLE LoginGegevens
ADD primary KEY (Username)
ALTER TABLE NawGegevensKind
ADD primary KEY (KindSpeler)
ALTER TABLE NawGegevensProfspeler
ADD primary KEY (ProfSpeler)
ALTER TABLE SpelerTeam
ADD primary KEY (Team,KindSpeler,ProfSpeler)
ALTER TABLE Toernooi
ADD primary KEY (Team,Rondes,Games)
-- relation
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Kindspeler)
REFERENCES NawGegevensKind(Kindspeler);
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Profspeler)
REFERENCES NawGegevensProfspeler(Profspeler);
ALTER TABLE Toernooi
ADD FOREIGN KEY (Team)
REFERENCES SpelerTeam(Team);

The Primary Key of SpelerTeam is Team,KindSpeler,ProfSpeler.
That means that any foreign key that references that table has to reference all three of those columns. You can't create a foreign key that uses only team.

You need an index on a colum so that it can be referenced as a foreign key efficiently. Add an index on SpelerTeam.Team and on all other columns with the same problem. Try CREATE INDEX IX_SpelerTeam_Team_Team ON SpelerTeam (Team);

Add below after all tables have been created:
CREATE UNIQUE NONCLUSTERED INDEX IX_SpelerTeam_Team
ON dbo.SpelerTeam (Team);
GO
As it was pointed in another answer you cannot reference to non unique column, to make column unique you can make this column primary key or create index for this column.
It is not enough that your "Team" column is part of composite key.

Related

Unable to add a constraint foreign key to a table from an already created table in SQL server management studio 18. Can someone help me?

I'm creating a database for my assignment. I had to create 2 tables namely Customer and Job through the "New Query" option in SQL server. After creating both of them, I wanted to add Job_ID (A primary key) from Job table as a foreign key to the Customer table. As I have already created the Customer table, The only option I had was to ALTER the customer table. But after altering, I seemed to get this unusual error.
Msg 1769, Level 16, State 1, Line 1
Foreign key 'Job_ID' references invalid column 'Job_ID' in referencing table 'CUSTOMER'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.
I can provide you with any more info if necessary.
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
CREATE TABLE JOB
(Job_ID INT NOT NULL PRIMARY KEY,
Pickup_location VARCHAR (10) NOT NULL,
Destination VARCHAR (10) NOT NULL,
Customer_ID INT FOREIGN KEY REFERENCES CUSTOMER(Customer_ID));
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
This looks like the same issue as described here.
When you try to create your foreign key:
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
You are saying that you want to use the field Job_ID from the table CUSTOMER:
ALTER TABLE CUSTOMER ADD FOREIGN KEY (Job_ID)
and that the values in this field should match values in the Job_ID column from the table JOB:
REFERENCES JOB(Job_ID);
The problem is that your CUSTOMER table doesn't have a Job_ID column, based on its definition:
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
The fields in the CUSTOMER table are Customer_ID,Customer_Name,Gender,Customer_Type,Addresss and Telephone_No.
So you either need to add a Job_ID column to the CUSTOMER table, or specify a different field to use in your ALTER TABLE statement - one which does exist in the CUSTOMER table.
More information on ALTER TABLE and ADD FOREIGN KEY specifically can be found here.

SQL Foreign Key

If someone can help me with this script I would greatly appreciate it.
So I am basically trying to use a Foreign Key to reference a table with multiple Primary Keys and I keep getting an Error. When I run the create table script for personal trainer, I get this error:
Msg 1776, Level 16, State 0, Line 3
There are no primary or candidate keys in the referenced table 'Schedule' that match the referencing column list in the foreign key 'FK__Personal_Trainer__38996AB5'.
Msg 1750, Level 16, State 0, Line 3
Could not create constraint or index. See previous errors.
Here is the CREATE TABLE script for both tables. I am trying to use a foreign key in personal trainer to reference the table in schedule. FitnessWebApp is the name of the database.
use FitnessWebApp
create table Schedule
(
day char(20),
time char(20),
name char(30),
gymName char(30)
primary key (name, gymName, day, time)
);
use FitnessWebApp
create table Personal_Trainer
(
name char(30),
gymName char(30)
primary key(name, gymName),
foreign key (name, gymName) REFERENCES Schedule(name, gymName)
);
Try this:
create table Personal_Trainer (
id int(10) not null,
trainerName char(30),
primary key (id));
create table gym (
id int(10) not null,
gymName char(30),
primary key (id));
create table Schedule (
id int (10) not null,
trainerId int(10),
gymId int(10),
gymDay Date,
gymTime Datetime,
primary key (id),
foreign key (trainerId) REFERENCES Personal_Trainer (id),
foreign key (gymId) REFERENCES gym (id));

relationship many to many

I want to create database with relationship many to many. But i have error
SQL71516 :: The referenced table '[dbo].[BookAuthors]' 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. SQL71516 :: The referenced table
'[dbo].[BookAuthors]' 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.
How to fix this?
CREATE TABLE [dbo].[BookAuthors] (
[Book] INT NOT NULL,
[Author] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Book] ASC,[Author] ASC)
);
CREATE TABLE [dbo].[Books] (
[Id] INT NOT NULL,
[Title] NVARCHAR (MAX) NULL,
[Price] MONEY NULL,
[Category] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
FOREIGN KEY ([Id]) REFERENCES [dbo].[BookAuthors] ([Book])
);
CREATE TABLE [dbo].[Authors] (
[Id] INT NOT NULL,
[Name] NCHAR (10) NOT NULL,
PRIMARY KEY CLUSTERED ([Id]),
FOREIGN KEY ([Id]) REFERENCES [dbo].[BookAuthors] ([Author])
);
You crated in you BookAuthors composite primary key which consists of two columns: Book and Author. When referencing it, you need to reference both columns.
Other solution is to make in BookAuthors third column (identity maybe) which would be primary key and reference that one.
The Following Image Shows you the Table Structure.

SQL Server foreign relationship on two-column primary key

I have the following three sample tables (simplified demo for purpose of question):
CREATE TABLE Teams
(
Id int IDENTITY(1,1) NOT NULL,
Name varchar(50) NOT NULL,
PRIMARY KEY (Id)
)
CREATE TABLE TeamGroups
(
Id int NOT NULL,
TeamId int NOT NULL,
PRIMARY KEY (Id,TeamId)
)
CREATE TABLE RoomBookings
(
Id int NOT NULL,
TeamGroupId int NOT NULL,
RoomId int NOT NULL,
PRIMARY KEY (Id)
)
and I have the following foreign key already set up:
ALTER TABLE TeamGroups WITH CHECK
ADD CONSTRAINT [FK_TeamGroups_Teams]
FOREIGN KEY (TeamId) REFERENCES Teams(Id)
The idea is that each Team can be in zero or more TeamGroups, and each TeamGroup can have zero or more RoomBookings
To reflect that, I want to add a foreign key from the RoomBookings table into the TeamGroups table.
I tried using the Relationships GUI in Management Studio to create the foreign key (primary key table: TeamGroups.ID, foreign key table: RoomBookings.TeamGroupId) but I get an error:
The columns in table 'TeamGroups' do not match an existing primary key
or UNIQUE constraint
I'm assuming it's because the TeamGroups table has a two-column primary key?
I don't really want to make a foreign key constraint from the TeamGroups table (eg, the key is present in the TeamGroups table), as the table will eventually be used by other tables (such as EquipmentBookings, GroupManagers, etc).
Any help?
If your primary key is made up from more than one columns, then all foregin keys also must have all those columns - there's no way around this.
But I don't understand why you'd get this error trying to link TeamGroups to Team based on the Team.Id column.... that should work just fine.
Try using this:
ALTER TABLE TeamGroups WITH CHECK
ADD CONSTRAINT [FK_TeamGroups_Teams]
FOREIGN KEY (TeamId) REFERENCES Teams(Id);
You had Teams (which is not a valid column in TeamGroups at all), and you had REFERENCES Teams.id which is wrong - it needs to be REFERNCES Teams(Id); (column in parenthesis - not the "dot" notation)
Update: from TeamGroups to RoomBookings - yes.... either use both columns from TeamGroups in your RoomBookings table - or what would stop you from making the TeamGroups.Id column an INT IDENTITY and then have the PK on just this one column?? Any good reason for that??
CREATE TABLE TeamGroups
(
TeamGroupId int NOT NULL,
TeamId int NOT NULL,
PRIMARY KEY (TeamGroupId)
)
ALTER TABLE dbo.RoomBookings
ADD CONSTRAINT FK_RoomBookings_TeamGroup
FOREIGN KEY TeamGroupId REFERENCES TeamGroups(TeamGroupId)

SQL Server 2008 - Create a Join Table

I'm having issues creating a simple join table (associative table, etc. whatever your flavor is).
These are test tables, so there is not much to them.
First table is
CREATE TABLE dbo.CareerField(
CareerFieldID int IDENTITY(1,1) NOT NULL,
CareerFieldName varchar(100) NOT NULL
)
Second Table is
CREATE TABLE dbo.Cluster(
ClusterID int IDENTITY(1,1) NOT NULL,
ClusterName varchar(100) NOT NULL
)
Third table (join table) to create a many-to-many relationship is
CREATE TABLE dbo.CareerField_Cluster(
CareerFieldID int NOT NULL,
ClusterID int NOT NULL
)
I am trying to set foreign keys in this third table using the following
ALTER TABLE dbo.CareerField_Cluster
ADD CONSTRAINT FK_CareerField_Cluster_CareerFieldID
FOREIGN KEY(CareerFieldID) REFERENCES dbo.CareerField(CareerFieldID)
ALTER TABLE dbo.CareerField_Cluster
ADD CONSTRAINT FK_CareerField_Cluster_ClusterID
FOREIGN KEY(ClusterID) REFERENCES dbo.Cluster(ClusterID)
However, I keep getting an error of
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'dbo.CareerField' that match the referencing column list in the foreign key 'FK_CareerField_Cluster_CareerFieldID'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
I try setting both fields as a primary key, but it will not allow me to select a separate table when creating the key - I can't select CareerFieldID to reference CareerField Table and then ClusterID to reference Cluster Table.
I've not had this issue with MySQL and I am new to SQL Server. Any help is much appreciated.
For each of your tables CareerField and Cluster, ensure you have a PK designated via the CONSTRAINT directive.
CREATE TABLE [dbo].[CareerField]
(
[CareerFieldID] [int] IDENTITY(1,1) NOT NULL,
[CareerFieldName] [varchar](100) NOT NULL,
CONSTRAINT [PK_Career] PRIMARY KEY CLUSTERED
(
[CareerFieldID] ASC
)
)

Resources