Why can't I reference in the column list? - sql

This is my first database, I created HOTEL, ROOM and GUEST tables, but when I execute the BOOKING table, it's not working.
The error is:
There are no primary or candidate keys in the referenced table 'ROOM'
that match the referencing column list in the foreign key
'FK_BOOKING_ROOM'
Scripts:
CREATE DATABASE HOTEL
USE HOTEL
CREATE TABLE HOTEL
(
HolCode varchar(20) UNIQUE NOT NULL,
Name varchar(30),
City varchar(20) DEFAULT 'Ha noi',
CONSTRAINT PK_HOLEL PRIMARY KEY (HolCode)
)
CREATE TABLE ROOM
(
RoomNo int,
HolCode varchar(20),
TypeRoom char(1) DEFAULT 'S',
Price double precision,
CONSTRAINT CHK_TYPE CHECK (TypeRoom = 'D' OR TypeRoom = 'S' OR TypeRoom = 'F'),
CONSTRAINT CHK_PRICE CHECK (10 <= Price AND Price <= 200),
CONSTRAINT PK_ROOM PRIMARY KEY (RoomNo, HolCode),
CONSTRAINT FK_ROOM FOREIGN KEY (HolCode) REFERENCES HOTEL(HolCode)
)
-- TAO BANG GUEST
CREATE TABLE GUEST
(
GuestNo int,
GuestName varchar(30),
Address varchar(50),
CONSTRAINT PK_GUEST PRIMARY KEY (GuestNo)
)
--TAO BANG BOOKING
CREATE TABLE BOOKING
(
HolNo varchar(20) NOT NULL,
GuestNo int NOT NULL,
DateFrom DateTime DEFAULT GETDATE(),
DateTo DateTime,
RoomNo int NOT NULL,
CONSTRAINT PK_BOOKING PRIMARY KEY (HolNo, DateFrom, RoomNo),
-- CONSTRAINT FK_BOOKING_HOTEL FOREIGN KEY (HolNo) REFERENCES HOTEL(Code),
CONSTRAINT FK_BOOKING_GUEST FOREIGN KEY (GuestNo) REFERENCES GUEST(GuestNo),
CONSTRAINT FK_BOOKING_ROOM FOREIGN KEY (RoomNo, HolCode)
REFERENCES ROOM(RoomNo, HolCode)
)
DROP TABLE BOOKING

Try:
CONSTRAINT FK_BOOKING_ROOM FOREIGN KEY (RoomNo,HolNo)
REFERENCES ROOM(RoomNo,HolCode)
Rooms aren't uniquely identified by just a RoomNo so the foreign key needs to have the hotel code also. I'd also suggest, just as a stylistic point, that you try to use the same names in every table where the contents should be the same - so either HolNo or HolCode, but not both.

Related

SQL queries - There are no primary or candidate > keys in the referenced table

I am trying to create some tables in SQL but when I am running these queries, I am getting the following exception:
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Couple' that match the referencing column list in the foreign key 'FK__wedding__CoupleN__2739D489'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
CREATE TABLE Person
(
FirstName nvarchar (25) NOT NULL,
SurName nvarchar (25) NOT NULL,
id char(9) PRIMARY KEY
CHECK (id LIKE REPLICATE('[0-9]',9)),
PhoneNumber char(10)
CHECK (PhoneNumber LIKE REPLICATE('[0-9]',10)),
Birthday date
CHECK ((GETDATE() - YEAR(Birthday)) > 10)
);
CREATE TABLE Couple
(
Number int identity(1000,1),
Partner1 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
Partner2 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
CoupleName varchar(25) NOT NULL,
CONSTRAINT PK_Couple1 CHECK (Partner1 <> Partner2),
CONSTRAINT PK_Couple PRIMARY KEY (Partner1, Partner2, Number)
);
CREATE TABLE weddinghall
(
Name varchar (25) PRIMARY KEY,
SeveralSeats int
CHECK (SeveralSeats >= 50 AND SeveralSeats <= 5000),
Kosher char(1)
CHECK (works = 'Y' OR not = 'N'),
PlaceType varchar(25)
CHECK (PlaceType IN s, 'b', 'd', 'doif')),
NumberOfParkingSpaces int
);
CREATE TABLE wedding
(
WeddingHallName varchar (25)
REFERENCES weddinghall(Name) ON DELETE CASCADE,
CoupleNumber int
REFERENCES Couple (Number) ON DELETE CASCADE,
WeddingDate date,
NumberOfGuests Int ,
CONSTRAINT PK_Wedding PRIMARY KEY (CoupleNumber, WeddingHallName)
);
CREATE TABLE WeddingGuests
(
GuestId char(9) references Person (Id) ON DELETE cascade,
CoupleNumber int references Couple (Number) ON DELETE cascade,
WeddingDate date,
WeddingHallName varchar (25) references weddinghall(Name) ON DELETE cascade,
ArrivalConfirmation CHAR(1),
ArrivingToWedding Char(1),
CONSTRAINT PK_WeddingGuests
PRIMARY KEY (GuestId, CoupleNumber, WeddingDate, WeddingHallName)
);
Can you please help?
The error message is telling you that you don't have a unique constraint or primary key on dbo.Couple.Number. That is the third key column in your primary key constraint, and you can't point a foreign key there. You can either:
Add a unique constraint on dbo.Couple.Number
Change the PK to a unique constraint and make dbo.Couple.Number the single-column primary key.

REFERENCING ISSUE

CREATE TABLE Loan
(
Customerid Char(9) NOT NULL,
EquipmentCode Char(5) NOT NULL,
StartDate DateTime NOT NULL,
EndDate DateTime NULL,
CONSTRAINT CHK_ID
CHECK (Customerid LIKE '[ST][0-9][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]'),
CONSTRAINT CHK_Date CHECK (EndDate >= StartDate),
CONSTRAINT Loan_PK PRIMARY KEY(Customerid),
CONSTRAINT CUST_FK
FOREIGN KEY(Customerid) REFERENCES CUST(CustomerID)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE EQUIPMENT
(
EquipmentCode CHAR(5) NOT NULL,
EquipmentName VARCHAR(50) NOT NULL,
Description VARCHAR(255) NULL,
RentalRatePerDay DECIMAL(4,2) NOT NULL,
CONSTRAINT EQP_PK PRIMARY KEY(EquipmentCode),
CONSTRAINT CHK_Rate CHECK (RentalRatePerDay BETWEEN 4 AND 50),
CONSTRAINT LOAN_FK
FOREIGN KEY(EquipmentCode) REFERENCES Loan(EquipmentCode)
ON UPDATE CASCADE
ON DELETE CASCADE
);
I was able to reference earlier on in the above loan.table but for the equipment table it states
Msg 1776, Level 16, State 0, Line 49
There are no primary or candidate keys in the referenced table 'Loan' that match the referencing column list in the foreign key 'LOAN_FK'.
Msg 1750, Level 16, State 1, Line 49
Could not create constraint or index. See previous errors.
Please advise.
When we create a ForeignKey on a dependent table, it MUST refer back to the PrimaryKey (or a Unique Key see: https://stackoverflow.com/a/18435114/1690217) on the principal table.
In your case, EQUIPMENT is the principal end of the relationship, and Loan is the dependent. What this means is that the FK needs to be on the Loan table instead, so you should have this:
CREATE TABLE EQUIPMENT
(
EquipmentCode CHAR(5) NOT NULL,
EquipmentName VARCHAR(50) NOT NULL,
Description VARCHAR(255) NULL,
RentalRatePerDay DECIMAL(4,2) NOT NULL,
CONSTRAINT EQP_PK PRIMARY KEY(EquipmentCode),
CONSTRAINT CHK_Rate CHECK (RentalRatePerDay BETWEEN 4 AND 50),
);
CREATE TABLE Loan
(
Customerid Char(9) NOT NULL,
EquipmentCode Char(5) NOT NULL,
StartDate DateTime NOT NULL,
EndDate DateTime NULL,
CONSTRAINT CHK_ID
CHECK (Customerid LIKE '[ST][0-9][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]'),
CONSTRAINT CHK_Date CHECK (EndDate >= StartDate),
CONSTRAINT Loan_PK PRIMARY KEY(Customerid),
CONSTRAINT CUST_FK
FOREIGN KEY(Customerid) REFERENCES CUST(CustomerID)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT EQUIPMENT_FK
FOREIGN KEY(EquipmentCode) REFERENCES EQUIPMENT(EquipmentCode)
ON UPDATE CASCADE
ON DELETE CASCADE
);
A foreign key references a primary key on another table. You have the FK on the wrong table

ERROR :ORA-02264: name already used by an existing constraint

create table ward
(
wnum int primary key,
wname varchar(30),
phoneno int,
wloc varchar(50),
chnursename varchar(20) constraint ward_fk references charge_nurse
);
create table charge_nurse
(
chnurse varchar(20) constraint charge_nurse_pk primary key,
stnum int constraint charge_nurse_fk references staff
);
create table staff
(
stname varchar(20),
stnum int constraint staff_pk primary key,
addr varchar(20),
phoneno int,
stposition varchar(30),
specality varchar(30) unique,
shift varchar(10),
noofhoursperweek int
);
create table generalsupplies
(
itnum int constraint generalsupplies_pk primary key,
itname varchar(20) unique,
quantityinstock int,
reorder varchar(10),
despt varchar(10),
costperunit int
);
create table pharmasupplies
(
dnum int constraint pharmasupplies_pk primary key,
dname varchar(30) unique,
despt varchar(20),
dosage_Mg int,
quantityinstock int,
reorder varchar(10),
costperunit int
);
While creating the below table I am facing problem:
ORA-02264: name already used by an existing constraint
create table centralsupplies
(
wardnum int constraint centralsupplies_fk references ward,
itemnum int constraint centralsupplies_fk references generalsupplies,
drugnum int constraint centralsupplies_fk references pharmasupplies,
quantity_required varchar(20),
staffname varchar(10) references staff(stname),
staffnum int constraint centralsupplies_fk references staff,
regnum int unique,
dateord date,
daterec date
);
How do I solve this problem?
You use 3 times the same constraint name centralsupplies_fk in your centralsupplies table.
3 constraints = 3 constraint names
Your create table statement has four foreign keys all called centralsupplies_fk. That is not allowed: constraint names must be unique within a schema. You must give each one a different name.
It is usual practice to include the referenced table in the key name. So
create table centralsupplies
(
wardnum int constraint centralsupplies_ward_fk references ward,
itemnum int constraint centralsupplies_generalsupplies_fk references generalsupplies,
drugnum int constraint centralsupplies_pharmasupplies_fk references pharmasupplies,
quantity_required varchar(20),
staffname varchar(10) references staff(stname),
staffnum int constraint centralsupplies_staff_fk references staff,
regnum int unique,
dateord date,
daterec date
)
Also you have another foreign key constraint on STAFFNAME which you have not named. You do not need to name constraints, the system will generate a unique one for you, but it's generally a good idea to name them, not least because it is easier to diagnose relational integrity error messages with meaningfully named constraints.
However, in this case the correct solution is to drop the STAFFNAME column. You already have a foreign on the STAFF table, and you should join to that table whenever you need to display a value for STAFFNAME. Besides you do not have a unique constraint on staff.stname column, so the foreign key statement will fail: foreign keys can only reference primary or unique keys.

Oracle: Constraints of keys

I have an entity within Oracle's SQL:
and I'm wondering, what does "UF" represent? I've written the SQL code but I do not know how to represent the "UF" attribute as a constraint.
CREATE TABLE entry (
entryno NUMBER(4) NOT NULL,
carndate DATE NOT NULL,
entrystarttime DATE NOT NULL,
entryfinishtime DATE NOT NULL,
entryplace NUMBER(4) NOT NULL,
charname VARCHAR2(30) NOT NULL,
compno NUMBER(4) NOT NULL,
eventypecode CHAR(3) NOT NULL,
teamname VARCHAR2(30) NOT NULL
);
ALTER TABLE entry ADD CONSTRAINT entry_pk PRIMARY KEY ( entryno,
carndate );
ALTER TABLE entry
ADD CONSTRAINT entry_charity_fk FOREIGN KEY ( charname )
REFERENCES charity ( charname );
ALTER TABLE entry
ADD CONSTRAINT entry_carnival_fk FOREIGN KEY ( carndate )
REFERENCES carnival ( carndate );
ALTER TABLE entry #
ADD CONSTRAINT entry_competitor_fk FOREIGN KEY ( compno )
REFERENCES competitor ( compno );
ALTER TABLE entry #
ADD CONSTRAINT entry_event_fk FOREIGN KEY ( carndate, eventypecode )
REFERENCES evenet ( carndate, eventypecode );
ALTER TABLE entry
ADD CONSTRAINT entry_team_fk FOREIGN KEY ( teamname, carndate )
REFERENCES team ( teamname,carndate );
ALTER TABLE entry
ADD CONSTRAINT ... ("UF")
The UF is actually two flags.
As you've recognised the F means the column is a foreign key. The U stands for Unique. Those columns form part of the compound unique key:
ALTER TABLE entry ADD CONSTRAINT entry_carnival_un UNIQUE
( carndate, compno, eventypecode );
carndate is also part of the compound primary key so really it should be flagged PFU but I guess the modelling tool didn't allow for three flags.

SQL no primary or candidate keys in the referenced table

Here's my problem when I write my SQLSever expressions:
There are no primary or candidate keys in the referenced table 'Room'
that match the referencing column list in the foreign key 'FK_Booking_RoomNo__4E298478'.
And some snapshots to my program:
CREATE TABLE Booking(
HotelNo NVARCHAR(4) not null,
GuestNo SMALLINT,
DateFrom DATETIME not null,
DateTo DATETIME,
RoomNo SMALLINT not null,
PRIMARY KEY (HotelNo,DateFrom,RoomNo),
FOREIGN KEY (HotelNo) REFERENCES Hotel(HotelNo),
FOREIGN KEY (GuestNo) REFERENCES Guest(GuestNo),
FOREIGN KEY (RoomNo) REFERENCES Room(RoomNo)); <---trouble on this line
CREATE TABLE Room(
RoomNo SMALLINT not null,
HotelNo NVARCHAR(4) not null,
RoomType NVARCHAR(25),
Price DECIMAL(5,2),
PRIMARY KEY (RoomNo,HotelNo),
CONSTRAINT fk_Room FOREIGN KEY (HotelNo) REFERENCES Hotel(HotelNo));
and here is the Hotel table
CREATE TABLE Hotel(
HotelNo NVARCHAR(4) not null,
HotelName NVARCHAR(25),
City NVARCHAR(25),
PRIMARY KEY (HotelNo) );
I tried to do some search on this problem, and it says this might be caused when there's no primary key defined in the table Room, but as above, it is defined.
Can someone please help me with this problem?
Thank you in advance.
Any reference to composite key must also include both columns.
FOREIGN KEY (RoomNo, HotelNo) REFERENCES Room(RoomNo, HotelNo))