How can I create a FOREIGN KEY in SQLite? - database

I have a table already created, here's the code:
CREATE TABLE "Préstamo_Biomédica" (
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Entregado CHAR(100),
Fech_Pres DATE,
Fech_Devu DATE,
Nota TEXT
)
And I'm trying to create a table with a FOREIGN KEY with this code:
CREATE TABLE Inventario_Biomédica (
Id_Pieza INT PRIMARY KEY,
Nom_Pieza CHAR(100),
Cantidad INT,
Des_Pieza TEXT,
Gastable BIT,
Fech_Ent DATE,
P_Módulo BIT,
FOREIGN KEY (ID) REFERENCES Préstamo_Biomédica(ID_Préstamo),
)
I hope you guys can help me...

You should use only ASCII characters in identifiers. If not, you must quote them.
To get an autoincrementing ID, you must use INTEGER, not INT.
The FOREIGN KEY clause refers to a column that already must exist in the table's column list.
And the parent's table/column names come after the REFERENCE:
CREATE TABLE "Inventario_Biomédica" (
Id_Pieza INTEGER PRIMARY KEY,
Nom_Pieza CHAR(100),
Cantidad INT,
Des_Pieza TEXT,
Gastable BIT,
Fech_Ent DATE,
"P_Módulo" BIT,
"ID_Préstamo" INT,
FOREIGN KEY ("ID_Préstamo") REFERENCES "Préstamo_Biomédica"(ID),
);

CREATE TABLE "Préstamo_Biomédica" (
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Entregado CHAR(100),
Fech_Pres DATE,
Fech_Devu DATE,
Nota TEXT
)
CREATE TABLE Inventario_Biomédica (
Id_Pieza INT PRIMARY KEY,
Nom_Pieza CHAR(100),
Cantidad INT,
Des_Pieza TEXT,
Gastable BIT,
Fech_Ent DATE,
P_Módulo BIT,
FOREIGN KEY (ID_Préstamo) REFERENCES Préstamo_Biomédica(ID),
)
Give foreign Key Column Name right after FOREIGN KEY and parent tables Primary key column after REFERENCES

Related

i need Database table creating

i created my tables and I'm stuck at the last one,
here is the tables that been created correctly
CREATE TABLE Staff (
Staff_ID INT NOT NULL PRIMARY KEY,
First_Name VARCHAR(50),
Last_Name VARCHAR(50),
Username VARCHAR(10),
Password VARCHAR(10),
Address VARCHAR(30)
)
CREATE TABLE Category (
Category_ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(30)
)
CREATE TABLE Author (
Author_ID INT NOT NULL PRIMARY KEY,
First_Name VARCHAR(50),
Last_Name VARCHAR(50),
Birth_Place VARCHAR(30),
Birth_Date DATE
)
CREATE TABLE Publisher (
Publisher_ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(50)
)
and this is the one I'm getting an error :
CREATE TABLE Book (
Book_ID INT NOT NULL PRIMARY KEY,
Title VARCHAR(50),
Edition INT(30),
Year_Published INT(4),
FOREIGN KEY (Publisher_ID) REFERENCES Publisher(Publisher_ID),
FOREIGN KEY (Author_ID) REFERENCES Author(Author_ID),
FOREIGN KEY (Category_ID) REFERENCES Category(Category_ID)
)
the error says:
"ORA-00907: missing right parenthesis"
INT can not have a scale associated with it so YEAR_PUBLISHED and EDITION are incorrect definitions.
I believe that, generally, you would be better off sticking to NUMBER for numeric datatypes, eg NUMBER(4), NUMBER(30).
In the database the INT datatype is simply a sub-type of NUMBER so you aren't gaining anything by using it:
type NUMBER is NUMBER_BASE;
subtype INTEGER is NUMBER(38,0);
subtype INT is INTEGER;
If you want to see the definitions for the various 'other' numeric datatypes take a look at the SYS.STANDARD package.
The INT data type does not have a precision.
You also need to define the Publisher_ID, Author_ID and Category_ID columns.
It is good practice to name your constraints.
A PRIMARY KEY column is both NOT NULL and UNIQUE so you do not need to include a second NOT NULL constraint.
Like this:
CREATE TABLE Book (
Book_ID INT CONSTRAINT Book__Book_id__PK PRIMARY KEY,
Title VARCHAR(50),
Edition INT,
Year_Published INT,
Publisher_ID INT CONSTRAINT Book__Publisher_ID__FK REFERENCES Publisher(Publisher_ID),
Author_ID INT CONSTRAINT Book__Author_id__FK REFERENCES Author(Author_ID),
Category_ID INT CONSTRAINT Book__category_ID__FK REFERENCES Category(Category_ID)
);

There are no primary or candidate keys in the referenced table

I have two tables:
Table1
c_ID float - PK
Field1
Field2
Field3
p_ID [uniqueidentifier]
and
Table2
p_ID nvarchar
s_ID float
where both p_ID and s_ID are part of the primary key.
I tried to create a foreign key on Table1:
ALTER TABLE Table1
ADD CONSTRAINT FK_Table1_Table2 FOREIGN KEY (p_ID)
REFERENCES Table2(p_ID)
and I got an error:
There are no primary or candidate keys in the referenced table
'dbo.Table2' that match the referencing column list in the foreign key
'FK_Table1_Table2'.
Am I getting this error because data type of p_ID is uniqueidentifier and in Table2 p_ID is nvarchar? Is there a workaround?
you just have to use a FK that includes the same columns that are in the PK
create table ParentTest (
SomeNumber int,
Name varchar(25),
PRIMARY KEY (SomeNumber, Name)
)
create table ChildTest (
SomeValue varchar(25),
SomeNumber int,
Name varchar(25),
FOREIGN KEY (SomeNumber, Name) references ParentTest (SomeNumber, Name)
)

Error while entering data into a table with Primary Key formed by multiple columns, each referenced from other tables

I have 4 tables, 3 of which have their own primary keys. In the 4th table, the primary keys of all the other 3 tables are referenced as foreign keys and these are made into a primary key (combination of all 3 foreign keys). However, upon entering data into the columns, I get constraint violation errors.
The code snippets are as below:
--Table # 1
create table PartSupplier(
partSupplierID int primary key,
fName varchar(20) NOT NULL,
lName varchar(20),
houseNO varchar(20),
streetName varchar(20),
city varchar(20),
dob date,
contactNo varchar(50)
)
--Table # 2
create table PartSpecialist(
partSpecialistID int primary key,
fName varchar(20) NOT NULL,
lName varchar(20),
houseNO varchar(20),
streetName varchar(20),
city varchar(20),
dob date,
contactNo varchar(15)
)
--Table # 3
create table CarPart(
partNumber int primary key,
description varchar (250),
vehicleID int NOT NULL,
imagePath varchar(50)
)
--Table # 4 (with multiple foreign keys made into one primary key)
create table SpecialistSuppliedPart(
partSpecialistID int NOT NULL,
partSupplierID int NOT NULL,
partNumber int NOT NULL,
condition varchar(10),
dateAcquired date,
costPrice int NOT NULL,
constraint specialist_supplier_part_PK primary key (partSpecialistID, partSupplierID, partNumber),
foreign key (partSpecialistID) references PartSpecialist(partSpecialistID),
foreign key (partSupplierID) references PartSupplier(partSupplierID),
foreign key (partNumber) references CarPart(partNumber)
)
I tried inserting the following values in the table:
3 3 5 USED 5000 2011-03-01
3 13 18 NEW 6000 2011-06-26
upon which I got the following error:
http://i.stack.imgur.com/HhFk2.jpg
where FK_SpecialistSuppliedPart_PartSupplier is the Foreign Key existing between Table # 1 and Table # 4.
I have all of these entries existing in the respective tables. After an exhaustive search on the internet (including stackoverflow.com), I could not find a solution.
What am I doing wrong here?
P.S. I tried adding the Foreign and Primary keys using MSSQLs Design Tool but it still results in the same error.

Foreign key contraints in a table on two columns referncing a same table

I have a table Item master, in which i have a primary key as item code
tbl_item_master
Itm_code int PK
Bill of material(tbl_Bom)
child_id int
parent_id int
I have another table of bill of material(tbl_bom) in which there are 2 columns of parent and child which are having their values which is nothin but primary key of item master. I.e parent and child id in BOM are from Item Master's primary key. Follwoing is my script that I am using to apply foreign key on child and parent .
CREATE TABLE dbo.BOM_MASTER
(
BOM_SrNo INT CONSTRAINT DF_BOM_MASTER_BOM_SrNo DEFAULT ((0)) NOT NULL,
BOM_Key INT NOT NULL,
PD_Key INT,
BOM_Level INT,
BOM_Parent_Code VARCHAR (50),
BOM_Child_Code VARCHAR (50),
BOM_UOM INT,
BOM_Qty DECIMAL (14, 2),
BOM_Final_Version INT,
BOM_ItemDimension_Applicable BIT,
BOM_MatType INT CONSTRAINT DF__BOM_MASTE__BOM_M__192BAC54 DEFAULT ((0)) NOT NULL,
CONSTRAINT FK_BOM_MASTER_Project_Details_Master FOREIGN KEY (PD_Key) REFERENCES dbo.Project_Details_Master (PD_Key),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Parent_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Child_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code)
)
GO
and I am getting the following error
Cannot create two constraints named 'FK_BOM_MASTER_tbl_itm_master'. Duplicate constraint names are not allowed. Severity 16
If you add newlines, the issue becomes apparent.
CREATE TABLE dbo.BOM_MASTER
(
BOM_SrNo INT CONSTRAINT DF_BOM_MASTER_BOM_SrNo DEFAULT ((0)) NOT NULL,
BOM_Key INT NOT NULL,
PD_Key INT,
BOM_Level INT,
BOM_Parent_Code VARCHAR (50),
BOM_Child_Code VARCHAR (50),
BOM_UOM INT,
BOM_Qty DECIMAL (14, 2),
BOM_Final_Version INT,
BOM_ItemDimension_Applicable BIT,
BOM_MatType INT CONSTRAINT DF__BOM_MASTE__BOM_M__192BAC54 DEFAULT ((0)) NOT NULL,
CONSTRAINT FK_BOM_MASTER_Project_Details_Master FOREIGN KEY (PD_Key) REFERENCES dbo.Project_Details_Master (PD_Key),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Parent_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Child_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code)
)
GO
The last 2 are named identically. It is also clear there are other naming issues. What is DF__BOM_MASTE__BOM_M__192BAC54? Will future users of the table be able to gleem anything from this naming?

foreign key references to a table problem here

create database Exer4
use Exer4
create table customer (
cus_code int,
constraint PK_customer primary key (cus_code),
cus_Lname varchar(20),
cus_Fname varchar (30),
cus_intial varchar (2),
cus_areacode int,
cus_phone int,
cus_balance float
)
create table charter (
char_trip int,
constraint PK_charter primary key (char_trip),
char_date date,
ac_number varchar(5),
foreign key(ac_number) references aircraft,
char_destination varchar(5),
char_distance float,
char_hours_flown float,
char_hours_wait float,
char_fuel_gallons float,
cus_code int,
foreign key(cus_code) references customer
)
create table aircraft(
ac_number varchar(5),
constraint PK_aircraft primary key(ac_number),
mod_code varchar(10),
foreign key(mod_code) references model,
ac_itaf varchar(10),
ac_tiel varchar(10),
ac_tier varchar(10),
)
create table model(
mod_code int,
constraint PK_model primary key(mod_code),
mod_manufacturer varchar(10),
mod_name varchar(10),
mod_seats int,
mod_chg_mile int,
)
create table crew (
char_trip int,
emp_num int,
constraint PK_crew primary key (char_trip,emp_num),
foreign key (char_trip) references charter,
foreign key(emp_num) references employee,
crew_job varchar(10)
)
create table rating (
rtg_code varchar(5),
rtg_name varchar (30),
constraint PK_rating primary key (rtg_code)
)
create table employee (
emp_num int,
constraint PK_employee primary key (emp_num),
emp_title varchar (4),
emp_lname varchar (20),
emp_fname varchar (30),
emp_initial varchar (2),
emp_dob date,
emp_hire_date date,
)
create table pilot (
emp_num int,
pl_license varchar (3),
pl_ratings varchar (30),
pl_med_type int,
pl_med_date date,
pl_pt135_date date,
constraint PK_pilot primary key (emp_num)
)
why is that when i reference to "aircraft" it said invalid table??
what is wrong with my code??
You have to specify which field to reference:
foreign key (mod_code) references model (mod_code),
The foreign key constraint consists of 2 parts:
ALTER TABLE aircraft
ADD CONSTRAINT fk_aircraft_model
FOREIGN KEY (mod_code) -- here you specify the field(s) to reference from in the aircraft table
REFERENCES model (mod_code) -- here you specify the field(s) to reference to in the model table
You are creating the tables in the wrong order. charter references aircraft but create table aircraft doesn't appear until later.

Resources