SQL Foreign Key - sql-server

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));

Related

SSMS Build: "The INSERT statement conflicted with the FOREIGN KEY constraint"

I'm getting this error even thought I think my table correctly references a primary key. The Constituent_Gift table references 5 foreign keys but only triggers this error for the Gift table. I can't see why the Category table would work but the Gift table wouldn't. The exact error message is:
Msg 547, Level 16, State 0, Line 12
The INSERT statement conflicted with the FOREIGN KEY constraint "fk_giftid". The conflict occurred in database "SusanCurtis", table "dbo.Gift", column 'Gift_ID'.
Code:
CREATE TABLE Category
(
Category_ID NCHAR(4) CONSTRAINT pk_categoryid PRIMARY KEY,
Category_Description NVARCHAR(50) CONSTRAINT nn_categorydescription NOT NULL
);
CREATE TABLE Gift
(
Gift_ID NCHAR(1) CONSTRAINT pk_giftid PRIMARY KEY,
Gift_Description NVARCHAR(20) CONSTRAINT nn_giftdescription NOT NULL,
);
CREATE TABLE Constituent_Gift
(
Constituent_Gift_ID NCHAR(6) CONSTRAINT pk_constituentgift PRIMARY KEY,
Constituent_ID NCHAR(6) CONSTRAINT fk_constituentid FOREIGN KEY
REFERENCES Constituent(Constituent_ID),
Gift_ID NCHAR(1) CONSTRAINT fk_giftid FOREIGN KEY
REFERENCES Gift(Gift_ID),
Fund_ID NCHAR(4) CONSTRAINT fk_fundid FOREIGN KEY
REFERENCES Fund(Fund_ID),
Event_ID NCHAR(2) CONSTRAINT fk_eventid FOREIGN KEY
REFERENCES [Event](Event_ID),
Category_ID NCHAR(4) CONSTRAINT fk_categoryid FOREIGN KEY
REFERENCES Category(Category_ID),
Note NVARCHAR(2000),
Gift_Amount MONEY CONSTRAINT nn_giftamount NOT NULL,
Deductible_Amount MONEY,
Gift_Date Date,
Payment_Type NVARCHAR(30),
Anonymous_Gift BIT
);
Does anyone know why this is happening?
Well, the error message really says it all: obviously, that INSERT (which unfortunately you haven't shown) is trying to insert a value that violates the foreign key constraint fk_giftid - that's the foreign key between Constituent_Gift.Gift_ID and Gift.Gift_ID - which means you're trying to insert a row into Constituent_Gift with a value for Gift_ID that doesn't exist in the referenced Gift table.
And that's the whole point of a foreign key constraint - ensure you only ever insert valid data - that is present in the referenced table (here Gift).
Fix that value to be something that is present in the Gift table - and you should be fine.
what data are you going to insert?
I also miss the schema for the table 'Constituent'
Constituent_ID NCHAR(6) CONSTRAINT fk_constituentid FOREIGN KEY
REFERENCES Constituent(Constituent_ID),

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.

Why am I getting an error 'Invalid table name', When i am trying to create another table with foreign key with the primray key of the first table

There is a parent table with the name of "SALESPERSON123" with primary key "SSN"
SQL> DESC SALESPERSON123;
Name Null? Type
----------------------------------------- -------- ----------------------------
SSN NOT NULL VARCHAR2(30)
NAME VARCHAR2(30)
START_YR NUMBER
DEPT_NO VARCHAR2(30)
I want to create another table "Trip" in which I want to make "SSN" the foreign key, but i am getting following error.
SQL> CREATE TABLE TRIP
2 (
3 TRIP_ID VARCHAR2(30),
4 SSN VARCHAR2(30),
5 FROM_CITY VARCHAR2(30),
6 TO_CITY VARCHAR2(30),
7 DEP_DATE NUMBER,
8 RETURN_DATE NUMBER,
9 FOREIGN KEY (SSN) REFERENCES TO SALESPERSON123(SSN),
10 PRIMARY KEY (TRIP_ID)
11 );
FOREIGN KEY (SSN) REFERENCES TO SALESPERSON123(SSN),
*
ERROR at line 9:
ORA-00903: invalid table name
I tried to multiple time, by deleting and again creating the parent table but no there is no avail.
Remove TO. It must be:
FOREIGN KEY (SSN) REFERENCES SALESPERSON123(SSN),
instead of
FOREIGN KEY (SSN) REFERENCES TO SALESPERSON123(SSN),
A foreign key is a way to enforce referential integrity within your Oracle database. A foreign key means that values in one table must also appear in another table.
The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.
A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

SQL Relation MORE on MORE

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.

SQL Server Foreign Key references invalid Table 'employees'

I try to run this SQL Server query:
USE DB_UBB;
CREATE TABLE dept_emp (
emp_no INT NOT NULL,
dept_no CHAR(4) NOT NULL,
from_date DATE NOT NULL,
to_date DATE NOT NULL,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no) ON DELETE CASCADE, -- Error here
FOREIGN KEY (dept_no) REFERENCES departments(dept_no) ON DELETE CASCADE, -- And here
PRIMARY KEY (emp_no, dept_no)
);
CREATE INDEX (emp_no);
CREATE INDEX (dept_no);
and I get these errors:
Foreign key 'FK__dept_emp__8bc6840bee39d6cef4bd' references invalid table 'employees'.
Foreign key 'fk__dept_emp__99bc0b2304d3f32059a9' references invalid table 'departments'.
even though I have these tables:
What do I do wrong?
EDIT:
Added Whole DB:
SQL ‘hides’ the columns from the Key of the Clustered Index in Nonclustered Indexes.
You have created a composite primary on both emp_no,dept_no
cluster index of primary will hide both columns from indexes in following queries and will generate error
CREATE INDEX (emp_no);
CREATE INDEX (dept_no);
If you are specifying the foreign key after the column specifications, try using the CONSTRAINT clause instead:
to_date DATE NOT NULL,
CONSTRAINT fk_dept_emp_dept FOREIGN KEY (emp_no) REFERENCES employees(emp_no) ON DELETE CASCADE,
CONSTRAINT fk_dept_emp_emp FOREIGN KEY (dept_no) REFERENCES departments(dept_no) ON DELETE CASCADE,
Aparently, I even though the tables were created, it didn't recognize them.
I added an <if not exist, create tables>
I also removed the CREATE INDEX (emp_no); and CREATE INDEX (dept_no); as #Muhammad Nasir said, but it didn't fix the referencing issue.
Solution:
USE DB_UBB;
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE name='employees' and xtype='U')
CREATE TABLE employees (
emp_no INT NOT NULL,
birth_date DATE NOT NULL,
first_name VARCHAR(14) NOT NULL,
last_name VARCHAR(16) NOT NULL,
gender VARCHAR(1) NOT NULL CHECK (gender IN('M', 'F')),
hire_date DATE NOT NULL,
PRIMARY KEY (emp_no)
);
GO
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE name='departments' and xtype='U')
CREATE TABLE departments (
dept_no CHAR(4) NOT NULL,
dept_name VARCHAR(40) NOT NULL,
PRIMARY KEY (dept_no),
UNIQUE (dept_name)
);
GO
IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE name='dept_emp' and xtype='U')
CREATE TABLE dept_emp (
emp_no INT NOT NULL,
dept_no CHAR(4) NOT NULL,
from_date DATE NOT NULL,
to_date DATE NOT NULL,
FOREIGN KEY (emp_no) REFERENCES employees(emp_no) ON DELETE CASCADE,
FOREIGN KEY (dept_no) REFERENCES departments(dept_no) ON DELETE CASCADE,
PRIMARY KEY (emp_no, dept_no)
);
GO

Resources