Why is the foreign key not accepted? - sql

Why is the table Room not accepting the foreign key?
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3)
)
ALTER TABLE Room
add foreign key(Roomtype)
references RoomType(Roomtype)
This is the error message I get when I run alter table.
Major Error 0x80040E11, Minor Error 0
ALTER TABLE Room
add foreign key(Roomtype)
references RoomType(Roomtype)
Invalid column ID. [ Roomtype ]

You need to add the foreign key as a field to the Room table before you attempt to declare the foreign key constraint.
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3)
)
ALTER TABLE Room
ADD Roomtype nvarchar(2) NOT NULL
ALTER TABLE Room
add constraint FK_Give_Me_A_Good_Name foreign key(Roomtype)
references RoomType(Roomtype)

The column must exist BEFORE you can FK to it.
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3),
RoomtypeA nvarchar(2) NOT NULL
)
ALTER TABLE [dbo].[Room] ADD CONSTRAINT FK_MyName FOREIGN KEY (RoomtypeA) REFERENCES dbo.Roomtype (Roomtype)
GO

Related

There are no primary or candidate keys in the referenced table 'tblgender' that match the referencing column list in the foreign key 'giFK'

create database my_data
create table tblperson(
pid int primary key,
pname varchar(15),
pgender varchar(15)
)
create table tblgender(
gid varchar(15) primary key,
gender varchar(15)
)
Alter table tblperson add constraint giFK
Foreign key (pgender) references tblgender(gid)

SQL Server - Invalid Table

I am fairly new to SQL and I can't understand why I am receiving an error when establishing foreign keys as I receive an error saying that the destination table is invalid.
Below is the SQL code, any advice on how to fix would be brilliant! :)
The error appears regarding tblFilms and tblCinemaScreens.
CREATE TABLE tblCustomer (
CustomerID int,
CustomerSurname NVARCHAR(25),
CustomerForename NVARCHAR(20),
CustomerAge int,
CustomerPhoneNumber NVARCHAR(12),
CustomerEmailAddress NVARCHAR(100),
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblBookings (
BookingID int,
FilmShowings TIME,
PriceOfFilm MONEY,
DateOfBooking DATE,
FilmID int,
CinemaScreenID int,
CustomerID int,
CONSTRAINT PK_tblBookings PRIMARY KEY CLUSTERED (BookingID),
CONSTRAINT FK_FilmID FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES tblCustomer(CustomerID)
)
GO
CREATE TABLE tblFilms (
FilmID int,
FilmName VARCHAR(100),
FilmDuration int,
AgeRating VARCHAR(3),
CriticScore int,
FilmDescription NVARCHAR(300),
FilmGenre NVARCHAR(20),
FilmStartScreeningDate DATE,
FlimEndScreeningDate DATE,
CinemaScreenID int,
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
CinemaScreenType NVARCHAR(10),
NumberOfSeats int,
FilmID int,
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID),
CONSTRAINT FK_tblCinemaScreens FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID)
)
GO
Cinema screens table does not need a film id and you need to create the tables BEFORE referencing them with FK's
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
CinemaScreenType NVARCHAR(10),
NumberOfSeats int,
FilmID int,
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID)
GO
CREATE TABLE tblFilms (
FilmID int,
FilmName VARCHAR(100),
FilmDuration int,
AgeRating VARCHAR(3),
CriticScore int,
FilmDescription NVARCHAR(300),
FilmGenre NVARCHAR(20),
FilmStartScreeningDate DATE,
FlimEndScreeningDate DATE,
CinemaScreenID int,
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
CREATE TABLE tblCustomer (
CustomerID int,
CustomerSurname NVARCHAR(25),
CustomerForename NVARCHAR(20),
CustomerAge int,
CustomerPhoneNumber NVARCHAR(12),
CustomerEmailAddress NVARCHAR(100),
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblFilms (
FilmID int,
FilmName VARCHAR(100),
FilmDuration int,
AgeRating VARCHAR(3),
CriticScore int,
FilmDescription NVARCHAR(300),
FilmGenre NVARCHAR(20),
FilmStartScreeningDate DATE,
FlimEndScreeningDate DATE,
CinemaScreenID int,
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
You are trying to create a foreign key on tables before they are made. Comment out the lines in the create table statements that are giving you an error and create the tables. Once the tables are made create the missing foreign keys you need like this:
alter table tblFilms
add CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
alter table tblBookings
add CONSTRAINT FK_FilmID FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID)
The answer is they should have not direct relationships
A film is shown on 0 or more screens
You need a join table
rblFilmCinema
filmID fk to tblFilms
screenID fk to tblCinemaScreens
composite PK on filmID, screenID
I would change up the schema some to give yourself more flexibility. I would assume that a film can be on more than one cinema screen so I would take CinemaScreenID off of tblFilms and remove the foreign key. You can also remove FilmID from tblBookings since you have the CinemaScreenID already which has the FilmID.. Another thing to consider might be having multiple films on the same CinemaScreen which would be another tabled called tblCinemaScreenFilms and you would put that CinemaScreenFilmID on the tblBookings instead
CREATE TABLE tblFilms (
FilmID int,
...
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
)
GO
CREATE TABLE tblCustomer (
CustomerID int,
...
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblBookings (
BookingID int,
CinemaScreenID int,
CustomerID int,
...
CONSTRAINT PK_tblBookings PRIMARY KEY CLUSTERED (BookingID),
CONSTRAINT FK_CinemaScreenID FOREIGN KEY (CinemaScreenID ) REFERENCES tblCinemaScreens(CinemaScreenID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES tblCustomer(CustomerID)
)
GO
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
FilmID int,
...
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID),
CONSTRAINT FK_tblCinemaScreens FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID)
)
GO
Option B (preferred)
CREATE TABLE tblCustomer (
CustomerID int,
...
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblFilms (
FilmID int,
...
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
)
GO
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
...
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID)
)
GO
CREATE TABLE tblCinemaScreenFilms (
CinemaScreenFilmID int,
CinemaScreenID int,
FilmID int
CONSTRAINT PK_tblCinemaScreenFilms PRIMARY KEY CLUSTERED (CinemaScreenFilmID),
CONSTRAINT FK_FilmID FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID),
CONSTRAINT FK_CinemaScreenID FOREIGN KEY (FilmID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
CREATE TABLE tblBookings (
BookingID int,
CustomerID int,
CinemaScreenFilmID int,
...
CONSTRAINT PK_tblBookings PRIMARY KEY CLUSTERED (BookingID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES tblCustomer(CustomerID),
CONSTRAINT FK_CinemaScreenFilmID FOREIGN KEY (CinemaScreenFilmID) REFERENCES tblCinemaScreenFilms(CinemaScreenFilmID)
)
GO
You're creating a table - tblFilms - and adding a foreign key to tblCinemaScreens before the second table has been created.
As a help I usually create all tables and then create any foreign key relationships and other constraints.

SQL Server 2012 creating tables and values

For some odd reason I can't create a table and because if that I can't insert any values into those tables. This is a new database and I am having a bit of a brain fart.. any help??? thanks
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY (Agencies)
)
Example of a working code
create table Agencies
(
AgencyID nvarchar(20) primary key,
AgName nvarchar(40),
AgAddress nvarchar(40),
AgPhone int
)
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(20) FOREIGN KEY REFERENCES Agencies(AgencyID)
)
Hope it helps!
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY REFERENCES Agencies(Your_Agencies_ID_COLUMN)
)
There two ways of creating foreign key constrain:
creating a foreign key constraint within the table definition
CREATE TABLE [dbo].[DataSource]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Pts] TINYINT
,[PtsOf] TINYINT
, CONSTRAINT [PK_DataSource] PRIMARY KEY ([SurveyInstanceID], [ProtoQuestionID])
);
CREATE TABLE [dbo].[DataSourceComments]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Comments] NVARCHAR(MAX)
,CONSTRAINT [FK_DataSourceComments_DataSource_SurveyInstanceID_ProtoQuestionID]
FOREIGN KEY ([SurveyInstanceID], [ProtoQuestionID])
REFERENCES [dbo].[DataSource] ([SurveyInstanceID], [ProtoQuestionID])
);
creating a foreign key constraint for existing table
CREATE TABLE [dbo].[DataSource]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Pts] TINYINT
,[PtsOf] TINYINT
,CONSTRAINT [PK_DataSource] PRIMARY KEY ([SurveyInstanceID], [ProtoQuestionID] )
);
CREATE TABLE [dbo].[DataSourceComments]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Comments] NVARCHAR(MAX)
);
ALTER TABLE [dbo].[DataSourceComments]
ADD CONSTRAINT [FK_DataSourceComments_DataSource_SurveyInstanceID_ProtoQuestionID]
FOREIGN KEY ([SurveyInstanceID], [ProtoQuestionID])
REFERENCES [dbo].[DataSource] ([SurveyInstanceID], [ProtoQuestionID]);
Note, that in both cases I am specifying the FK constraint name. It's is a recommended to have some naming convention which to apply to all new FK.
I believe your foreign key is incorrect... maybe try this?
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY REFERENCES Agencies(AgencyID)
)
Supposing "AgencyID" is the ID in your Agencies Table.
Try the below code
CREATE TABLE Agency
(
AgencyID INT PRIMARY KEY IDENTITY,
Name NVARCHAR(20)
)
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID INT FOREIGN KEY REFERENCES Agency(AgencyID)
)
First you have to create the parent table ie, Agency table. Then create the child (Customers) and refer the parent.

Why is sql showing me an error when creating a foreign key?

I am trying to insert Roomtype primary key into Room table as a foreign key but shows me with the following error
Major Error 0x80040E11, Minor Error 0
CREATE TABLE Room (
RoomID nvarchar(8),
Capacity numeric(3),
CONSTRAINT FK_TYPE foreign key (Roomtype) references RoomType(Roomtype)
)
Invalid column ID. [ Roomtype ]
CREATE TABLE Room (
RoomID nvarchar(8) ,
Capacity numeric(3),
CONSTRAINT FK_TYPE foreign key (Roomtype) references RoomType(Roomtype)
)
create table RoomType(
Roomtype nvarchar(2) primary key,
Description nvarchar(20),
Responsibility nvarchar(20)
)
you need to add roomtype column in Room table. You are creating foreign key to a non-existent column
create table RoomType ( Roomtype nvarchar(2) primary key,
Description nvarchar(20), Responsibility nvarchar(20)
)
CREATE TABLE Room ( RoomID nvarchar(8) , Capacity numeric(3),Roomtype nvarchar(2),
CONSTRAINT FK_TYPE foreign key (Roomtype) references RoomType(Roomtype)
)

Alter Table syntax Assignment

I have Assignment due in which i'm stuck on a question.
Add a “Sales Detail” table to your database. This table is related to the Orders and Products tables. It shows the product and quantity ordered at least (add other fields if you wish but explain why you added them on your paper).
There is no description of this table on the diagram provided. Use your best database design skills here!
Create Table SalesDetail
(
SaleDetailID int,
ProductID char(5),
ManufactureID char(3) not null,
OrderNo int,
qtyOrdered int
PRIMARY
)
Alter Table SalesDetail
Add FOREIGN KEY (ProductID)
REFERENCES Products(ProductID)
My Error is I can not get it to link SalesDetail table to Products table.
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Products' that match the referencing column list in the foreign key 'FK__SalesDeta__Produ__5EBF139D'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Create Table Customers
(
CustomerNo char(4)
Constraint ck_CustomerNoHas4positionsWithNumbers
Check(CustomerNo like'[0-9],[0-9],[0-9],[0-9]'),
Company varchar(50) not null,
CustomerRep char(3),
CreditLimt money default(20000.00),
PRIMARY KEY(CustomerNo)
)
Create Table Salesreps
(
EmployeeNo char(3)
Constraint ck_EmployeeNoHasDigits check(EmployeeNo like'[0-9],[0-9],[0-9]'),
FirstName varchar(25) not null,
LastName varchar(25) not null,
Age int,
SalesRepOffice char(2) not null,
Title varchar(50),
HireDate Date not null,
Manager char(3) not null,
Quota money,
Sales money not null,
PRIMARY KEY(EmployeeNo)
)
Create Table Offices
(
Office char(2) Constraint ck_checkOfficeHasNumbersOnly check(Office like'[0-9],[0-9]'),
City varchar(25) not null,
Region varchar(10) not null,
Manager char(3) not null,
Target money,
Sales money not null
PRIMARY KEY(Office)
)
Create Table Orders
(
OrderNo int,
OrderDate Date not null,
CustomerNo char(4) not null,
SalesRep char(3) not null
PRIMARY KEY(OrderNo)
)
Create Table Products
(
ManufactureID char(3)
Constraint ck_ManufactureIDifItHasLettersOnly check(ManufactureID like'[a-z],[a-z],[a-z]'),
ProductID char(5)
Constraint ck_ProductIDhasTwoLettersAndThreeNumbers check(ProductID like'[0-9],[0-9],[a-z],[a-z],[a-z]'),
Description varchar(50) not null,
Price money not null,
QtyOnHand int not null,
PRIMARY KEY(ManufactureID, ProductID)
)
--Add Foreign Keys to all tables who needs them
Alter Table Customers
Add constraint fk_customerrep
FOREIGN KEY (CustomerRep)
REFERENCES Salesreps(EmployeeNo)
Alter Table Salesreps
Add constraint fk_salesrepoffice
FOREIGN KEY (SalesRepOffice)
REFERENCES Offices(Office),
constraint fk_manager
FOREIGN KEY (Manager)
REFERENCES Salesreps(EmployeeNo)
Alter Table Offices
Add constraint fk_officesmanger
FOREIGN KEY (Manager)
REFERENCES Salesreps(EmployeeNo)
Alter Table Orders
Add constraint fk_customerno
FOREIGN KEY (CustomerNo)
REFERENCES Customers(CustomerNo),
constraint fk_salesrep
FOREIGN KEY (SalesRep)
REFERENCES Salesreps(EmployeeNo)
The table Products has a composite key (ManufactureID, ProductID), so you cannot uniquely identify a product by just the ProductId. Therefore you have to create a composite foreign key that references to both ManufactureId and ProductID:
Alter Table SalesDetail
Add FOREIGN KEY (ManufactureId, ProductID)
REFERENCES Products(ManufactureID, ProductID)
ProductID is not a primary key like the error says. In your code
PRIMARY KEY(ManufactureID, ProductID)
This creates a primary key that both of those columns combined.
The primary key for Products is (ManufactureID, ProductID). So the SalesDetail table should contain both these columns, and both should be part of the foreign key constraint:
Alter Table SalesDetail
Add FOREIGN KEY (ManufactureID, ProductID)
REFERENCES Products(ManufactureID, ProductID)