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

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.

Related

SQL ALTER TABLE foreign key

I have a problem with adding foreign keys with alter table command. I don't know how to make it so it works.
I need to add ISIK_ID and STAADION_ID to ISIK_STAADIONIL table as foreign key.
Here is my code:
CREATE TABLE ISIK(
ISIK_ID INT NOT NULL,
EESNIMI VARCHAR(25) NOT NULL,
PEREKONNANIMI VARCHAR(25) NOT NULL,
ISIKUKOOD VARCHAR(20),
KODAKONDSUS VARCHAR(30),
SUGU CHAR(1) NOT NULL,
HARIDUSTASE CHAR(1) NOT NULL,
TELEFONI_NR VARCHAR(20),
SYNNIPAEV DATE,
CONSTRAINT ISIK_ID_PK PRIMARY KEY (ISIK_ID)
);
CREATE TABLE ISIK_STAADIONIL(
ISIK_STAADIONIL_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP
);
CREATE TABLE STAADION(
STAADION_ID INT NOT NULL,
NIMETUS VARCHAR(20),
KIRJELDUS VARCHAR(100),
ASUKOHT VARCHAR(50),
SUURUS VARCHAR(20),
MAHUTAVUS INT,
EHITATUD VARCHAR(20),
EHITAJA VARCHAR(20),
CONSTRAINT STAADION_ID_PK PRIMARY KEY (STAADION_ID)
);
ALTER TABLE ISIK_STAADIONIL
ADD CONSTRAINT ISIK_ID_FK
FOREIGN KEY(ISIK_ID)
REFERENCES ISIK(ID);
You need to add the columns first (to the table) before you can create FK constraints using them.
CREATE TABLE ISIK_STAADIONIL(
ISIK_STAADIONIL_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_STAADIONIL_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP,
ISIK_ID INT,
STAADION_ID INT
);
And then your ALTER statement should work fine.
UPDATE
Changing the table-design slightly would make more sense, as per following. The logic is that ISIK_ID and STAADION_ID would together be sufficient to determine uniqueness in the ISIK_STAADIONIL table, so a separate ID is redundant:
CREATE TABLE ISIK_STAADIONIL(
ISIK_ID INT NOT NULL,
STAADION_ID INT NOT NULL,
CONSTRAINT ISIK__STAADIONIL_ID_PK PRIMARY KEY (ISIK_ID, STAADION_ID),
ALATES TIMESTAMP,
KUNI TIMESTAMP
);

Error when creating table in Oracle Database 11g SQL

I'm new to SQL and I'm trying to create a new table however I get an error when I run my script in the SQL command line, the errors I'm getting are either ORA-00942 missing right parenthesis or ORA-00942 table or view does not exist.
Oh and yes I know I have probably written some terrible script but as mentioned earlier I'm learning so any meaningful criticism would be appreciated along with some help :).
CREATE TABLE Branch
(
Branch_ID varchar(5),
Branch_Name varchar(255),
Branch_Address varchar(255),
Branch_Town varchar(255),
Branch_Postcode varchar(10),
Branch_Phone varchar(50),
Branch_Fax varchar(50),
Branch_Email varchar(50),
Property_ID varchar(5),
Contract_ID varchar(5),
Staff_ID varchar(5),
PRIMARY KEY (Branch_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_Id),
FOREIGN KEY (Contract_ID) REFERENCES Contract(Contract_Id),
FOREIGN KEY (Staff_ID) REFERENCES Staff(Staff_Id)
);
CREATE TABLE Staff
(
Staff_ID varchar(5),
Staff_Forename varchar(255),
Staff_Surname varchar(255),
Staff_Address varchar(255),
Staff_Town varchar(255)
Staff_Postcode varchar(10),
Staff_Phone varchar(50),
Staff_DOB varchar(50),
Staff_NIN varchar(10),
Staff_Salary varchar(50),
Staff_Date_Joined varchar(100),
Staff_Viewing_Arranged varchar(100),
Branch_ID varchar(5),
Sales_ID varchar(5),
PRIMARY KEY (Staff_ID),
FOREIGN KEY (Branch_ID) REFERENCES Branch(Branch_ID),
FOREIGN KEY (Sales_ID) REFERENCES Sales(Sales_Id)
);
CREATE TABLE Sales
(
Sales_ID varchar(5),
Property_Address varchar(255),
Property_Town varchar(255)
Property_Postcode varchar(10),
Property_Type varchar(255),
Num_Rooms varchar(50),
Date_of_Sale varchar(10),
Sales_Bonus varchar(100),
Branch_ID varchar(5),
Property_ID varchar(5),
Staff_ID varchar(5)
Seller_ID varchar(5),
PRIMARY KEY (Sales_ID),
FOREIGN KEY (Branch_ID) REFERENCES Branch(Branch_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_Id),
FOREIGN KEY (Staff_ID) REFERENCES Staff(Staff_Id),
FOREIGN KEY (Seller_ID) REFERENCES Seller(Seller_Id)
);
CREATE TABLE Contract
(
Contract_ID varchar(5),
Contract_Signed_Date varchar(50),
Property_ID varchar(5),
Buyer_ID varchar(5),
Seller_ID varchar(5),
Branch_ID varchar(5),
PRIMARY KEY (Contract_ID),
FOREIGN KEY (Branch_ID) REFERENCES Branch(Branch_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_Id),
FOREIGN KEY (Seller_ID) REFERENCES Seller(Seller_Id),
FOREIGN KEY (Buyer_ID) REFERENCES Buyer(Buyer_Id)
);
CREATE TABLE Buyer
(
Buyer_ID varchar(5),
Viewing_Data varchar(255),
Maximum_Budject varchar(255),
Purchase_Price varchar (50),
Buyer_Forename varchar(255),
Buyer_Surname varchar(255),
Buyer_Address varchar(255),
Buyer_Town varchar(255),
Buyer_Postcode varchar(10),
Property_ID varchar(5),
Contract_ID varchar(5),
Survey_ID varchar(5),
PRIMARY KEY (Buyer_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID),
FOREIGN KEY (Contract_ID) REFERENCES Contract(Contract_Id),
FOREIGN KEY (Survey_ID) REFERENCES Survey(Survey_Id)
);
CREATE TABLE Seller
(
Seller_ID varchar(5),
Seller_Forename varchar(255),
Seller_Surname varchar(255),
Seller_Address varchar(255),
Seller_Town varchar(255),
Seller_Postcode varchar(10),
Seller_Property_ID varchar(5),
No_of_Bed varchar(5),
Contract_ID varchar(5),
Property_ID varchar(5),
Sales_ID varchar(5),
PRIMARY KEY (Seller_ID),
FOREIGN KEY (Contract_ID) REFERENCES Contract(Contract_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_Id),
FOREIGN KEY (Sales_ID) REFERENCES Sales(Sales_Id)
);
CREATE TABLE Property
(
Property_ID varchar(5),
Property_Address varchar(255),
Property_Town varchar(255),
Property_Postcode varchar(10),
Asking_Price varchar(20),
Date_Registered varchar(50),
Property_Fixtures varchar(255),
Size_of_Rooms varchar(100),
Buyer_ID varchar(5),
Staff_ID varchar(5),
Contract_ID varchar(5),
Seller_ID varchar(5),
PRIMARY KEY (Property_ID),
FOREIGN KEY (Buyer_ID) REFERENCES Buyer(Buyer_ID),
FOREIGN KEY (Seller_ID) REFERENCES Seller(Seller_ID),
FOREIGN KEY (Staff_ID) REFERENCES Staff(Staff_Id),
FOREIGN KEY (Contract_ID) REFERENCES Contract(Contract_Id)
);
CREATE TABLE Survey
(
Survey_ID varchar(5),
No_of_Survey varchar(10),
Survey_Type varchar(255),
Organised_By varchar(255),
Property_ID varchar(5),
Staff_ID varchar(5),
Buyer_ID varchar(5),
PRIMARY KEY (Survey_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID),
FOREIGN KEY (Staff_ID) REFERENCES Staff(Staff_Id),
FOREIGN KEY (Buyer_ID) REFERENCES Buyer(Buyer_Id)
);
CREATE TABLE Advert
(
Survey_ID Advert_ID varchar(5),
No_of_Adverts varchar(10),
Advert_Website varchar(255),
Advert_Newspaper varchar(255),
Property_ID varchar(5),
PRIMARY KEY (Advert_ID),
FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID)
);
STAFF Table miss a , at the end
Staff_Town varchar(255)
Sales Table too
Property_Town varchar(255)
Staff_ID varchar(5)
Also you can't define constrains to table not created yet. I could found the error removing those constrain.
Can't define the foreign key references until the table being referred to is created. So, if the foreign key references are circular, in that A => B => C => A, they you will first have to create the tables, then use ALTER TABLE to define the foreign keys. Otherwise, create the tables in order, where first you create a table, then create the table that is referencing it.
Your script references tables that haven't been created yet. I.e., look at your first create table. by that time, STAFF and other tables don't exist yet, but you're setting them as foreign key references.
You should create your tables first, and then apply constraints after the dependencies are in place, using alter:
ALTER TABLE BRANCH
ADD CONSTRAINT fk_staff_id
FOREIGN KEY (Staff_ID) REFERENCES Staff(Staff_Id);
because you have tables that references each other you need create the references after the tables are created
--create table Buyer
CREATE TABLE Buyer
(
Buyer_ID varchar(5),
Property_ID varchar(5),
PRIMARY KEY (Buyer_ID)
);
--create table Property
CREATE TABLE Property
(
Property_ID varchar(5),
Buyer_ID varchar(5),
PRIMARY KEY (Property_ID)
);
--now you can set your reference constraints
ALTER TABLE Property Add FOREIGN KEY (Buyer_ID) REFERENCES Buyer(Buyer_ID);
ALTER TABLE Buyer Add FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID);
Your syntax is not clear on your keys.
Here is an example of what a create table with a primary key and a foreign key (fk) would look like:
CREATE TABLE animals (
animal_id NUMBER(10) PRIMARY KEY,
animal_name VARCHAR2(50) NOT NULL,
animal_species_code NUMBER(50) NOT NULL
CONSTRAINT fk_animal_species REFERENCES animal_species
(species_code));
It appears that the modeling in this set of tables might benefit from some additions and changes.
As an example, the STAFF table references the BRANCH table - but BRANCH also references STAFF. This means that BRANCH can only reference one STAFF, and vice versa, which I suspect is not what's wanted. It appears that you want a many-to-many relationship between BRANCH and STAFF, and the standard solution for enabling this is a junction table - one which contains the primary keys of both tables. Such a junction table between BRANCH and STAFF might look like:
CREATE TABLE BRANCH_STAFF
(BRANCH_ID VARCHAR(5)
CONSTRAINT BRANCH_STAFF_FK1
REFERENCES BRANCH(BRANCH_ID),
STAFF_ID VARCHAR(5)
CONSTRAINT BRANCH_STAFF_FK2
REFERENCES STAFF(STAFF_ID),
CONSTRAINT PK_BRANCH_STAFF
PRIMARY KEY (BRANCH_ID, STAFF_ID)
USING INDEX);
Best of luck.

PSQL Error there is no unique constraint matching given keys for referenced table

I have a baseball database. I'm getting the error Error there is no unique constraint matching given keys for referenced table pitcher.
Here's the schema
CREATE TABLE Teams(
Name varchar(30) NOT NULL Primary Key,
Record varchar(10)
);
CREATE TABLE Player(
Name varchar(30) NOT NULL,
Num int NOT NULL,
TeamName varchar(22) references Teams(Name),
PRIMARY KEY(Name, Num, TeamName),
Constraint NumCheck Check (Num < 100 and Num > -1)
);
CREATE TABLE Pitcher(
PHanded varchar(10),
PName varchar(30),
PTeamName varchar(30),
PNum int,
PRIMARY KEY(PName, PTeamName, PNum),
foreign key (PName, PTeamName, PNum) references Player(Name, TeamName, Num)
);
CREATE TABLE PosPlayer(
PPHanded varchar(10),
Position varchar(2),
PPName varchar(30),
PPNum int,
BTeamName varchar(30),
PRIMARY KEY(PPName, PPNum, BTeamName),
foreign key (PPName, PPNum, BTeamName) references Player(Name, Num, TeamName)
);
CREATE TABLE Games(
Id int Primary Key,
SchedDate DATE,
PlayedDate DATE,
HomeName varchar(30),
VisitName varchar(30),
Winner varchar(30)
);
CREATE TABLE Pitches
(
PID int,
Outcome varchar(10),
Bcount int,
Scount int,
Runners int,
Type varchar(10),
Speed int,
Pitchnum int,
PitName varchar(30) references Pitcher(PName),
PitNum int references Pitcher(PNum),
PitTeamName varchar(30) references Pitcher(PTeamName),
BatName varchar(30) references PosPlayer(PPName),
BatNum int references PosPlayer(PPNum),
BatTeamName varchar(30) references PosPlayer(BTeamName),
HomeTName varchar(30),
VisitTName varchar(30),
GId int references Games(Id),
foreign key (PitName, PitNum, PitTeamName) references Pitcher (PName, PNum, PTeamName),
foreign key (BatName, BatNum, BatTeamName) references PosPlayer (PPName, PPNum, BTeamName),
Primary Key(PID, PitName, PitNum, PitTeamName, BatName, BatNum, BatTeamName, GID),
Constraint Balls Check (Bcount > -1 and Bcount < 4),
Constraint Scount Check (Scount > -1 and Scount < 3)
);
In the other threads I looked up it was suggested to add a unique identifier, but in this schema it is possible to have the same name and be on the same team. How do I fix this?
The lines
CREATE TABLE Pitches
(
{...}
PitName varchar(30) references Pitcher(PName),
PitNum int references Pitcher(PNum),
PitTeamName varchar(30) references Pitcher(PTeamName),
BatName varchar(30) references PosPlayer(PPName),
BatNum int references PosPlayer(PPNum),
BatTeamName varchar(30) references PosPlayer(BTeamName),
{...}
)
are almost certainly the ones causing you grief. You're trying in each case to reference a nonunique column in the referenced table, and that just won't work.
The good news is that you don't need these references clauses, as they're taken care of by the table-level FOREIGN KEY clauses, each of which references a group of columns whose concatenated values are unique, due to being a composite primary key.

Keep getting an error when trying to create a foreign key in 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

Foreign key on a Foreign key - SQL Server

I'm creating a database for a project in which I need to declare a foreign key on another foreign key for the sake of a checking constraint.
I have a Person table and a Groups table, both of these contain a DepartmentID. Whenever I insert a new task in the Task table, I want to check that the Groups.DepartmentID matches the Person.DepartmentID.
The idea is that a task is linked to a person and has 2 types, a grouptype which defines if its database work, financial work etc and a tasktype which defines if its maintenance, training etc. When a person tries to add a task with a groupType that is not for his/her department it should fail.
I tried adding these attributes to the Task table as a foreign key, however declaring a foreign key on a non-unique or non-primary key isn't accepted in Microsoft SQL Server (the DepartmentID in the Person and Group tables cannot be unique!).
Anyone knows how to fix this?
CREATE TABLE Department
(
ID int PRIMARY KEY IDENTITY,
Name varchar(50),
UNIQUE ("Name")
)
CREATE TABLE Groups
(
ID int IDENTITY,
GroupType varchar(50) PRIMARY KEY,
Description varchar(255) DEFAULT ('-'),
DepartmentID int
FOREIGN KEY (DepartmentID) REFERENCES Department(ID),
)
CREATE TABLE Person
(
ID int PRIMARY KEY IDENTITY,
Name varchar(50),
DepartmentID int
FOREIGN KEY (DepartmentID) REFERENCES Department(ID)
)
CREATE TABLE TaskType
(
ID int IDENTITY,
TaskType varchar(50) PRIMARY KEY,
Description varchar(255) DEFAULT ('-'),
)
CREATE TABLE Task
(
ID int IDENTITY,
TimeFrame decimal(4,2),
Yearcount int,
GroupType varchar(50),
TaskType varchar(50),
WeekNr int,
ExceptionDetail varchar(255) DEFAULT ('-'),
PersonID int
)
These are the FK attributes in the task table that are not accepted:
GDID int FOREIGN KEY REFERENCES Groups(DepartmentID),
PDID int FOREIGN KEY REFERENCES Person(DepartmentID),
CHECK (GDID = PDID),
UNIQUE ("TaskType", "GroupType", "WeekNr", "Yearcount"),
FOREIGN KEY (TaskType) REFERENCES TaskType(TaskType),
FOREIGN KEY (PersonID) REFERENCES Person(ID),
FOREIGN KEY (GroupType) REFERENCES Groups(GroupType)
Add wider "super keys" to these tables that include the primary key and additional columns1, then declare the foreign keys using them. Whether you also remove the superfluous smaller foreign keys is a matter of taste:
CREATE TABLE Groups(
ID int IDENTITY,
GroupType varchar(50) PRIMARY KEY,
Description varchar(255) DEFAULT ('-'),
DepartmentID int FOREIGN KEY (DepartmentID) REFERENCES Department(ID),
constraint Group_Dep_XRef UNIQUE (GroupType,DepartmentID)
)
CREATE TABLE Person(
ID int PRIMARY KEY IDENTITY,
Name varchar(50),
DepartmentID int FOREIGN KEY (DepartmentID) REFERENCES Department(ID),
constraint Person_Dept_XRef UNIQUE (ID,DepartmentID)
)
CREATE TABLE Task(
ID int IDENTITY,
TimeFrame decimal(4,2),
Yearcount int,
GroupType varchar(50),
TaskType varchar(50),
WeekNr int,
ExceptionDetail varchar(255) DEFAULT ('-'),
PersonID int,
DepartmentID int,
constraint FK_Group_Dept_XRef FOREIGN KEY (GroupType,DepartmentID)
references Group (GroupType,DepartmentID),
constraint FK_Person_Dept_XRef FOREIGN KEY (PersonID,DepartmentID)
references Person (ID,DepartmentID),
UNIQUE ("TaskType", "GroupType", "WeekNr", "Yearcount"),
FOREIGN KEY (TaskType) REFERENCES TaskType(TaskType),
FOREIGN KEY (PersonID) REFERENCES Person(ID), --Redundant now
FOREIGN KEY (GroupType) REFERENCES Groups(GroupType) --Also redundant
)
(I also consolidated GDID and PDID into DepartmentID - if they're always meant to be equal, why store that twice and then have to have another constraint to assert their equality?)
1If a primary key (or unique key) is sufficient to uniquely identify each row then any wider key which includes the key columns and additional columns must also be sufficient to uniquely identify each row.