Keep getting an error when trying to create a foreign key in sql? - sql

CREATE TABLE Room (
RoomID nvarchar(8) PRIMARY KEY,
Capacity numeric(3)
)
CREATE TABLE RoomType (
RoomType nvarchar(2) primary key,
Description nvarchar(20),
Responsiblity nvarchar(20)
)
alter table Room
add constraint fk_type foreign key (Type) references RoomType(Type)
Major Error 0x80040E11, Minor Error 0
alter table Room
add constraint fk_type foreign key (Type) references RoomType(Type)
Invalid column ID. [ Type ]

You can create a table RoomEquipment that combines RoomID and EquipmentType like this:
create table RoomEquipment (
RoomID int,
EquipmentType nvarchar(1),
primary key (roomid, equipmenttype),
constraint fk_roomequipment_equipment_type
foreign key (equipmenttype)
references equipment(equipmenttype),
constraint fk_roomequipment_equipment_roomid
foreign key (roomid)
references room(roomid)
);
Other tables may look like this:
-- I prefer using char datatype for predictable number of characters in a field
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
);
-- You could use char(1) instead of nvarchar(1) for type; I'd prefer using int instead
create table Equipment (
Equipmenttype nvarchar(1) NOT NULL,
Description nvarchar(10)
);
-- Added a unique key to assist with good foreign key relationship
alter table Equipment add constraint uk_equipment_equipmenttype unique (equipmenttype);
-- Just use an int or char if roomID length is predictable
Create table Room (
RoomID nvarchar(8),
Capacity numeric(3),
Roomtype(fk,nvarchar(2)
);
alter table room add constraint uk_room_id unique (roomid);
Example is here: http://sqlfiddle.com/#!3/f510b

Related

"You cannot add or change a record because a related record is required in table"

I am running into the error
You cannot add or change a record because a related record is required in table
whenever I try to add a new entry to my tables. Here is my SQL code:
SQL DDL
CREATE TABLE ART_OBJECT
(
Id_no NUMBER PRIMARY KEY,
Artist VARCHAR(20),
Year INT UNIQUE,
Title VARCHAR(20),
Description VARCHAR(20),
Style VARCHAR(20) UNIQUE
);
ALTER TABLE ART_OBJECT
ADD CONSTRAINT ArtistName FOREIGN KEY (Artist) REFERENCES ARTIST(Name)
ALTER TABLE ART_OBJECT
ADD CONSTRAINT EName FOREIGN KEY (Title) REFERENCES EXHIBITIONS(Name)
CREATE TABLE ARTIST
(
Name VARCHAR(20),
DateBorn DATE,
Date_died DATE ,
Country_of_origin VARCHAR(20),
Epoch INT,
Main_style VARCHAR(20),
Description VARCHAR(20)
);
ALTER TABLE ARTIST
ADD CONSTRAINT TimeMade FOREIGN KEY (Epoch) REFERENCES ART_OBJECT(Year)
CREATE TABLE PERMANENT_COLLECTION
(
Date_acquired DATE,
Status VARCHAR(20),
Cost NUMBER,
Year INT,
ArtID NUMBER
);
ALTER TABLE PERMANENT_COLLECTION
ADD CONSTRAINT TimeMade FOREIGN KEY (Year) REFERENCES ART_OBJECT(Year)
ALTER TABLE PERMANENT_COLLECTION
ADD CONSTRAINT PCID FOREIGN KEY (ArtID) REFERENCES ART_OBJECT(Id_no)
CREATE TABLE BORROWED
(
Id_no NUMBER,
Name VARCHAR(20),
Date_borrowed DATE,
Date_returned DATE
);
ALTER TABLE BORROWED
ADD CONSTRAINT BID FOREIGN KEY (Id_no) REFERENCES ART_OBJECT(Id_no)
ALTER TABLE BORROWED
ADD CONSTRAINT BName FOREIGN KEY (Name) REFERENCES COLLECTIONS(CName)
CREATE TABLE PAINTING
(
Paint_type VARCHAR(20),
Drawn_on VARCHAR(20),
Style VARCHAR(20),
ArtID NUMBER
);
ALTER TABLE PAINTING
ADD CONSTRAINT PStyle FOREIGN KEY (Style) REFERENCES ART_OBJECT(Style)
ALTER TABLE PAINTING
ADD CONSTRAINT PID FOREIGN KEY (ArtID) REFERENCES ART_OBJECT(Id_no)
CREATE TABLE SCULPTURE
(
Material VARCHAR(20),
Height VARCHAR(20),
Weight VARCHAR(20),
Style VARCHAR(20),
ArtID NUMBER
);
ALTER TABLE SCULPTURE
ADD CONSTRAINT SCStyle FOREIGN KEY (Style) REFERENCES ART_OBJECT(Style)
ALTER TABLE PAINTING
ADD CONSTRAINT SCID FOREIGN KEY (ArtID) REFERENCES ART_OBJECT(Id_no)
CREATE TABLE STATUE
(
Material VARCHAR(20),
Height VARCHAR(20),
Weight VARCHAR(20),
Style VARCHAR(20),
ArtID NUMBER
);
ALTER TABLE STATUE
ADD CONSTRAINT STStyle FOREIGN KEY (Style) REFERENCES ART_OBJECT(Style)
ALTER TABLE STATUE
ADD CONSTRAINT STID FOREIGN KEY (ArtID) REFERENCES ART_OBJECT(Id_no)
CREATE TABLE OTHER
(
Type VARCHAR(20),
Style VARCHAR(20),
ArtID NUMBER
);
ALTER TABLE OTHER
ADD CONSTRAINT OStyle FOREIGN KEY (Style) REFERENCES ART_OBJECT(Style)
ALTER TABLE OTHER
ADD CONSTRAINT OID FOREIGN KEY (ArtID) REFERENCES ART_OBJECT(Id_no)
CREATE TABLE COLLECTIONS
(
CName VARCHAR(20) PRIMARY KEY,
Type VARCHAR(20),
Description VARCHAR(20),
Address VARCHAR(20),
Phone VARCHAR(20),
Contact_person VARCHAR(20),
);
CREATE TABLE EXHIBITIONS
(
Name VARCHAR(20) PRIMARY KEY,
Start_date DATE,
End_date DATE,
E_id NUMBER,
);
ALTER TABLE EXHIBITIONS
ADD CONSTRAINT EID FOREIGN KEY (E_id) REFERENCES ART_OBJECT(Id_no)
CREATE TABLE EXHIBITS_IN
(
Id_no NUMBER,
CName VARCHAR(20)
);
ALTER TABLE EXHIBITS_IN
ADD CONSTRAINT EIID FOREIGN KEY (Id_no) REFERENCES ART_OBJECT(Id_no)
ALTER TABLE EXHIBITS_IN
ADD CONSTRAINT EIName FOREIGN KEY (CName) REFERENCES COLLECTIONS(CName)
Database relations table for reference:
DB Relations Table
EER diagram for reference:
EER Diagram

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.

Problem in creating new table ORA-00906: missing left parenthesis

Here is my instruction :
it works on my friend computer !
CREATE TABLE typeRdv1(
id_type int PRIMARY KEY,
des VARCHAR(20)
);
CREATE TABLE rdv1(
id_rdv int PRIMARY KEY,
cin_pat VARCHAR(20),
date_rdv VARCHAR NOT NULL,
type_rdv VARCHAR(20),
state VARCHAR(20),
CONSTRAINT `FK_cin_rdv` FOREIGN KEY (cin_pat)
REFERENCES patients(cin_pat) ON DELETE NO ACTION,
CONSTRAINT `FK_id_type_rdv` FOREIGN KEY (type_rdv)
REFERENCES typeRdv1(id_type) ON DELETE NO ACTION
);
A ORA-00906: missing left parenthesis
Any help !
Please make sure all the "varchar" fields has a length defined. In your second table, it says: date_rdv VARCHAR NOT NULL, which I believe causing the issue, so try to change it into date_rdv VARCHAR(50) NOT NULL and try again.
...
CREATE TABLE rdv1(
id_rdv int PRIMARY KEY,
cin_pat VARCHAR(20),
date_rdv VARCHAR(50) NOT NULL, --length added to varchar
type_rdv VARCHAR(20),
state VARCHAR(20),
...
EDIT:
The reason you get "invalid character" error is that you cannot use "on delete no action" while creating a table with a constraint. Instead you should alter your table after to create your constraints with "on delete cascade" option. Probably like below ( you may need to drop your constraints first):
CREATE TABLE patients(
cin_pat int PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE typeRdv1(
id_type int PRIMARY KEY,
des VARCHAR(20)
);
CREATE TABLE rdv1(
id_rdv int PRIMARY KEY,
cin_pat VARCHAR(20),
date_rdv VARCHAR(50) NOT NULL,
type_rdv VARCHAR(20),
state VARCHAR(20)
);
alter table rdv1 add (
CONSTRAINT FK_cin_rdv FOREIGN KEY (cin_pat)
REFERENCES patients (cin_pat) ON DELETE cascade,
CONSTRAINT FK_id_type_rdv FOREIGN KEY (type_rdv)
REFERENCES typeRdv1 (id_type) ON DELETE cascade
);
Check this for more details: https://www.haidongji.com/2006/07/24/defining-no-action-foreign-key-constraints-in-oracle/comment-page-1/

column "parent_id" referenced in foreign key constraint does not exist when creating SQL table

I am new in SQL and trying to understand Foreign key syntax. I know this was asked in multiple questions but each question I found did not seem to teach me what I am doing wrong here.
This is my SQL code:
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
CREATE TABLE Adult
(
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
CREATE TABLE Shop
(
id int primary key
);
CREATE TABLE Drink
(
name varchar(30) primary key
);
CREATE TABLE AlcoholicDrink
(
FOREIGN KEY (name) REFERENCES Drink(name)
);
CREATE TABLE NonAlcoholicDrink
(
FOREIGN KEY (name) REFERENCES Drink(name)
);
And this is the error I am getting:
ERROR: column "parent_id" referenced in foreign key constraint does not exist
SQL state: 42703
You need to add fields in your tables to make the reference. Something like this :
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
minor_id serial primary key,
parent_id int,
other_fields text etc.
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
This is simply the reason why it's not working.
Like this
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
parent_id int ,
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
To add an answer without just a code snippet:
You've got the right idea with FOREIGN KEY (parent_id) REFERENCES Customer(id). This bit adds a constraint or a "rule" to your table. This constraint ensures that parent_id holds a real id in your Customer table.
The error message told us that column "parent_id" referenced in foreign key constraint does not exist. The confusion comes, understandably, from mistaking the constraint declaration for a column declaration.
As others have pointed out, we need to both 10 declare the foreign key constraint and 2) declare the column.
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
parent_id int, -- Declare the column
FOREIGN KEY (parent_id) REFERENCES Customer(id) -- Declare the constraint
);

I'm trying to alter one of my tables and adding a foreign key it I keep getting the same error

The error I get is:
Msg 1769, Level 16, State 1, Line 30
Foreign key 'fk_pid' references invalid column 'P_ID' in referencing table 'Detainee'.
My table structure:
create table Detainee
(
D_ID bigint primary key identity not null,
Fname nvarchar(50),
Lname nvarchar(50),
Address varchar(200),
DateOfBirth date,
DateOfArrest date,
SourceOfArrest nvarchar(max)
);
create table PrisonCell
(
P_ID bigint primary key not null,
Capacity int,
RemCap int,
C_Type varchar(20)
);
Code to alter table:
alter table Detainee
add constraint fk_pid foreign key(P_ID) references PrisonCell(P_ID)
What you need to do is:
add the column P_ID BIGINT to your table Detainee
then add the FK constraint to that column
Just adding the FK constraint to the table isn't going to automagically add a column as well...
You should be able to do this in a single step:
ALTER TABLE Detainee
ADD P_ID BIGINT
CONSTRAINT fk_pid FOREIGN KEY REFERENCES PrisonCell(P_ID);