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)
)
Related
I am using Microsoft SQL Server and trying to add a foreign key to the "Orders" table that references the primary key in my "Customer" table. I keep getting this message:
Msg 1769, Level 16, State 1, Line 28
Foreign key 'orders_customerid_fk' references invalid column 'CustomerID' in referencing table 'Orders'.
Msg 1750, Level 16, State 0, Line 28
Could not create constraint or index. See previous errors.
CREATE TABLE Customer
(
CustomerID INT NOT NULL PRIMARY KEY,
fName varchar(40),
lName varchar(40),
City varchar(40),
Country varchar(40),
Phone varchar(20)
);
CREATE TABLE Supplier
(
SupplierID INT NOT NULL PRIMARY KEY,
CompanyName varchar(40),
ContactName varchar(50),
ContactTitle varchar(40),
City varchar(40),
Country varchar(40),
Phone varchar(30),
Fax varchar(30),
);
CREATE TABLE Orders
(
OrderID INT NOT NULL PRIMARY KEY,
OrderDate datetime,
OrderNumber varchar(10),
TotalAmount decimal(12,2)
);
ALTER TABLE Orders
ADD CONSTRAINT Orders_CustomerID_FK
FOREIGN KEY(CustomerID) REFERENCES Customer(CustomerID);
You are missing the column that should receive the constrain of FK.
ALTER TABLE Orders
ADD CustomerID INT NULL; /*Adds a new int column existing rows will be
given a NULL value for the new column*/
Or
ALTER TABLE Orders
ADD CustomerID INT NOT NULL DEFAULT(0);
And then you can
ALTER TABLE Orders
ADD CONSTRAINT Orders_CustomerID_FK
FOREIGN KEY(CustomerID)
REFERENCES Customer(CustomerID)
;
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)
);
I have a question about using primary keys and foreign keys in an object relational database in oracle. Below is my sql code and insert statements. I am trying to create a simple database with student, course, teacher and department. but whenever I run the below select statement, I do not see the DepartmentID and TeacherID that I entered. Instead i get [HR.DEPARTMENT_OBJTYP] as the value for departmentID and likewise for teacherID. is this because I have referenced the whole department rather than just the departmentID in the course table? I do not know how to use foreign keys and query them properly in an object relational database, and have not been able to find any useful easy to understand info on it. could someone please show me where I am going wrong?
for example in Course_objtyp I do... TeacherID REF Teacher_objtyp. is this the correct way to reference, I am not sure as i only want to reference the teacherID not the whole Teacher_objtyp?
CREATE TYPE Student_objtyp AS OBJECT (
FName VARCHAR2(20),
LName VARCHAR2(20),
StudentID NUMBER
);
/
CREATE TABLE Student_objtab OF Student_objtyp (StudentID PRIMARY KEY)
OBJECT IDENTIFIER IS PRIMARY KEY;
CREATE TYPE Department_objtyp AS OBJECT (
DeptID NUMBER,
DeptName VARCHAR2(20)
);
/
CREATE TABLE Department_objtab OF Department_objtyp (DeptID PRIMARY KEY)
OBJECT IDENTIFIER IS PRIMARY KEY;
CREATE TYPE Teacher_objtyp AS OBJECT (
TeacherID NUMBER,
FName VARCHAR2(20),
LName VARCHAR2(20)
);
/
CREATE TABLE Teacher_objtab OF Teacher_objtyp (TeacherID PRIMARY KEY)
OBJECT IDENTIFIER IS PRIMARY KEY;
CREATE TYPE Course_objtyp AS OBJECT (
CourseName VARCHAR(20),
CourseID NUMBER,
DeptID REF Department_objtyp,
TeacherID REF Teacher_objtyp
);
/
CREATE TABLE Course_objtab OF Course_objtyp (
PRIMARY KEY (CourseID),
FOREIGN KEY (DeptID) REFERENCES Department_objtab,
FOREIGN KEY (TeacherID) REFERENCES Teacher_objtab)
/
INSERT INTO Student_objtab VALUES('bill','smitts',1);
INSERT INTO Student_objtab VALUES('bob','jo',2);
INSERT INTO Teacher_objtab VALUES(1,'Mr','Higgins');
INSERT INTO Department_objtab VALUES(1111,'Science');
INSERT INTO Course_objtab
SELECT 'Chem101',001,
REF(D),
REF(T)
FROM Department_objtab D, Teacher_objtab T
WHERE D.DeptID = 1111 and T.TeacherID = 1;
the very simple select statement i am trying to run:
select * from Course_objtab;
The below works fine but I am not sure if you are looking for that.
CREATE TYPE Course_objtyp AS OBJECT (
CourseName VARCHAR(20),
CourseID NUMBER,
DeptID Number,
TeacherID Number
);
CREATE TABLE Course_objtab OF Course_objtyp (
PRIMARY KEY (CourseID),
FOREIGN KEY (DeptID) REFERENCES Department_objtab(DeptID),
FOREIGN KEY (TeacherID) REFERENCES Teacher_objtab(TeacherID));
INSERT INTO Course_objtab
SELECT 'Chem101',001, D.DeptID, T.TeacherID
FROM Department_objtab D, Teacher_objtab T
WHERE D.DeptID = 1111 and T.TeacherID = 1;
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.
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.