SQL ALTER TABLE foreign key - sql

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

Related

Error in create table T-SQL "Incorrect syntax near ','."

When create table have error "Incorrect syntax near ','."
I cant see this error in code. Please point out this error.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc),
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR CONSTRAINT,
first_name VARCHAR CONSTRAINT,
middle_name VARCHAR,
phone_number INT(11),
address VARCHAR,
ticket_number INT CONSTRAINT,
date_registration DATETIME,
date_reregistratiom DATETIME,
issued_books_id FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
You cannot add multiple primary keys to the table, either composite ey (combination of two fields) or Unique constraint can be added instead.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
this is an error, you cannot ass multiple primary keys. Instead you can add Unique constraint
Correction would be,
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null Unique, --this is used to create the second table
quantity INT NOT null,
inventory_numbers INT NOT NULL Unique )
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc), --Referenced column needs to be unique
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR (255),
first_name VARCHAR (255),
middle_name VARCHAR(255),
phone_number INT,
[address] VARCHAR(255),
ticket_number INT ,
date_registration DATETIME,
date_reregistratiom DATETIME)
You cannot use a foreign key of another table as a foreign key for some other table. You need to read more on table, Primary key constraints and foreign key referencing.
This cannot be done. you are trying to refer to the foreign key of issued_books table as a foreign key in readers table, which is wrong.
issued_books_id INT FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
I hope this explanation will give you a better understanding of errors. There were synatx errors as well as wrong use of the SQL table creation steps. I have added the corrected code for you. Feel free to contact any time.

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/

Can't figure out how to make a subquery

CREATE TABLE TBLTeams
(
teamnm varchar(30) NOT NULL,
teamid varchar(10),
rondenm varchar(10)
primary key(teamnm)
)
CREATE TABLE TBLWedstrijd
(
thuisteamnm varchar(30) NOT NULL,
uitteamnm varchar(30) NOT NULL,
wedstrijdid varchar(10)
primary key(wedstrijdid)
)
alter table TBLWedstrijd add foreign key (thuisteamnm) references TBLTeams(teamnm)
alter table TBLWedstrijd add foreign key (uitteamnm) references TBLTeams(teamnm)
CREATE TABLE TBLUitslag
(
thuisteamnm varchar(30) NOT NULL,
uitteamnm varchar(30) NOT NULL,
wedstrijdid varchar(10) NOT NULL,
uitteampunt int,
thuisteampunt int
primary key(thuisteamnm)
)
alter table TBLUitslag add foreign key (wedstrijdid) references TBLWedstrijd(wedstrijdid)
If I update teamnm in TBLTeams how can I update reference in TBLWedstrijd uitteamnm. I know its a subquery but I really dont know how.
You're going about it a bit wrong. If you're going to change the teamname, you shouldn't use it as a key (Since that will break all references).
You'll want to reference their IDs from the TBLWedstrijd instead of using their name.
So your statements will become:
CREATE TABLE TBLWedstrijd
(
wedstrijdid varchar(10),
thuisteamid varchar(10) NOT NULL,
uitteamid varchar(10) NOT NULL,
primary key(wedstrijdid)
)
alter table TBLWedstrijd add foreign key (thuisteamid) references TBLTeams(teamid)
alter table TBLWedstrijd add foreign key (uitteamid) references TBLTeams(teamid)
The same is valid for your table TBLUitslag, you should only reference TBLWedstrijd, since that one already holds the info about which teams are playing. Not to mention, the score is pretty much part of a game anyway so it doesn't make a lot of sense to seperate those into 2 tables. So that becomes:
CREATE TABLE TBLWedstrijd
(
wedstrijdid varchar(10),
thuisteamid varchar(10) NOT NULL,
uitteamid varchar(10) NOT NULL,
uitteampunt int,
thuisteampunt int
primary key(wedstrijdid)
)
This is called "table normalisation" if you wanted to google some stuff for more info about it.

SQL SMS - Error - There is already an object named "genre" in the database

I'm trying to create a hypothetical videostore database and this error message comes up everytime I execute this query:
DROP DATABASE videostore
CREATE DATABASE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
CREATE TABLE classification
(
rating VARCHAR(2) NOT NULL CONSTRAINT classification_pk PRIMARY KEY,
description VARCHAR(100) NOT NULL,
minimum_age INT NULL,
);
CREATE TABLE format
(
format_id INT NOT NULL CONSTRAINT format_pk PRIMARY KEY IDENTITY,
format_name VARCHAR(8) NOT NULL,
purchase_cost FLOAT NOT NULL
);
CREATE TABLE rental_cost
(
rental_cost_id INT NOT NULL CONSTRAINT rental_cost_pk PRIMARY KEY IDENTITY,
rental_name VARCHAR(15) NOT NULL,
rental_cost FLOAT NOT NULL,
rental_days TINYINT NOT NULL
);
CREATE TABLE customer
(
customer_id INT NOT NULL CONSTRAINT customer_pk PRIMARY KEY IDENTITY,
first_name VARCHAR(20) NOT NULL,
surname VARCHAR(20) NOT NULL,
dob DATETIME NOT NULL,
home_address VARCHAR(50) NOT NULL,
contact_number VARCHAR(10) NOT NULL,
referrer_id INT NULL FOREIGN KEY REFERENCES customer(customer_id),
);
CREATE TABLE movie
(
movie_id INT NOT NULL CONSTRAINT movie_pk PRIMARY KEY IDENTITY,
movie_name VARCHAR(40) NOT NULL,
year SMALLINT NOT NULL,
duration SMALLINT NULL,
descrip VARCHAR(120) NULL,
classification VARCHAR(2) NOT NULL FOREIGN KEY REFERENCES classification(rating),
rental_cost_id INT NOT NULL FOREIGN KEY REFERENCES rental_cost(rental_cost_id),
);
CREATE TABLE copy
(
copy_id INT NOT NULL CONSTRAINT copy_pk PRIMARY KEY IDENTITY,
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
format_id INT NOT NULL FOREIGN KEY REFERENCES format(format_id),
);
CREATE TABLE rental
(
rental_id INT NOT NULL CONSTRAINT rental_pk PRIMARY KEY IDENTITY,
copy_id INT NOT NULL FOREIGN KEY REFERENCES copy(copy_id),
customer_id INT NOT NULL FOREIGN KEY REFERENCES customer(customer_id),
rental_date DATETIME NOT NULL,
return_date DATETIME NULL
);
CREATE TABLE genre_movie
(
genre_id INT NOT NULL FOREIGN KEY REFERENCES genre(genre_id),
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
CONSTRAINT genre_movie_pk PRIMARY KEY (genre_id, movie_id)
);
(Sorry it's not in the correct format for reading a script with ease, I just really couldn't work out how to do that.)
Basically when I execute the SQL script it tells me that the object 'genre' already exists, but I can't see it anywhere else in my code.
And the table shouldn't already exist because I drop the database each time the script is executed right?
Sidenote - if there's a better way to make it so the database is dropped only if it exists please help me with that also.
Appreciate it.
I think you need to add USE videostore after the CREATE DATABASE videostore. Otherwise you are creating tables in whatever database you are currently in.
I think you are executing this in the context of the master database. If you check it you will probably see all your tables are actually in master.
Change the first part to this:
DROP DATABASE videostore
CREATE DATABASE videostore
USE videostore
CREATE TABLE genre
It's generally best to execute sql statements when required - try:
DROP DATABASE videostore
GO
CREATE DATABASE videostore
GO
USE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
GO
etc.