Associative table is erroring - sql-server

I have a school project where I need to create a database in SQL Server. I am currently having issues entering in my tables.
I have successfully entered in the first two tables, but the associative table is erroring, as are other tables following.
create table Home
(
HomeID INT Identity (1,1) Primary key,
Address1 varchar(250) not null,
City varchar(25) not null,
State1 varchar(25) not null,
Zipcode CHAR(5) not null,
SmokeDetectors INT,
Co2Detectors INT,
SecuritySystem CHAR(1),
TotalSqFt int,
Rooms INT,
AdditionalBuilding CHAR(1),
AssessedValue DEC(10,2),
YearAssessed char(4),
CompanyID int not null,
)
create table MortgageCompany
(
CompanyID INT Identity (1,1) Primary key,
CompanyName varchar(100) not null,
Address1 varchar(250),
City varchar(25),
State1 varchar(25),
Zipcode char(5),
HomeID int not null
)
create table HomeMortgageCompany
(
HomeID INT,
CompanyID INT,
foreign key CompanyID references MortgageCompany(CompanyID),
foreign key HomeID references Home(HomeID),
Primary key (HomeID,CustomerID)
)
create table Loan
(
LoanID INT Identity (1,1) Primary key,
LoanNumber int not null,
MortgageAmount dec(10,2),
CompanyID int
foreign key CompanyID references MortgageCompany(CompanyID)
)
create table PersonalProperty
(
PropertyID INT Identity (1,1) Primary key,
ItemName int,
Type1 varchar(150) not null,
Value1 Dec(10,2) not null,
HomeID int
foreign key HomeID references Home(HomeID)
)
create table Policy
(
PolicyID INT Identity (1,1) Primary key not null,
PolicyYear char(4),
PremiumCharged dec(10,2),
EffectiveDate date not null,
ExpirationDate date not null,
ReviewDateTime datetim,
Decision char(8),
HomeID int
foreign key HomeID references Home(HomeID)
)
create table Bank
(
AccountID int Identity (1,1) Primary Key,
BankName varchar(150) not null,
AccountNumber int not null,
RoutingNumber int not null,
Amount Dec(10,2),
PolicyID int not null
)
create table PolicyBank
(
PolicyID int,
AccountID INT,
foreign key PolicyID references Policy(PolicyID),
foreign key AccountID references Bank(AccountID),
Primary Key (PolicyID, AccountID)
)
Create table PolicyHolder
(
SSN char(9) Primary key not null,
FirstName varchar(50) not null,
LastName varchar(50) not null,
)
create table PolicyPolicyHolder
(
SSN char(9),
PolicyID INT,
foreign key PolicyID references Policy(PolicyID),
foreign key SSN references PolicyHolder(SSN),
Primary key (SSN, PolicyID)
)
create table HomePolicyHolder
(
SSN char(9),
HomeID Int,
foreign key HomeID references Home(HomeID),
foreign key SSN references PolicyHolder(SSN),
Primary key (SSN, HomeID)
)
create table Employment
(
SSN char(9) Primary Key,
EmployerFirstName varchar(50)not null,
EmployerLastName varchar(50) not null,
Address1 varchar(250),
City varchar(25),
State1 varchar(25),
Zipcode char(5),
StartDate date,
CurrentSalary dec(10,2) not null,
JobTitle varchar (75),
RecordExtractionDate date not null,
foreign key SSN references PolicyHolder(SSN)
)
Create table Document
(
DocumentID INT Identity (1,1) Primary key,
DocumentType varchar(50),
DateTimeSent datetime not null,
SSN char(9) not null,
PolicyID int,
foreign key PolicyID references Policy(PolicyID)
)
create table PolicyHolderDocument
(
DocumentID int,
SSN char(9),
foreign key DocumentID references Document(DocumentID),
foreign key SSN references PolicyHolder(SSN)
);

For the third table definition:
create table HomeMortgageCompany (
HomeID INT,
CompanyID INT,
foreign key CompanyID references MortgageCompany(CompanyID),
foreign key HomeID references Home(HomeID),
Primary key (HomeID,CustomerID)
)
Problems with this code:
the column name in the defina of the foreign key needs to be surrounded with parentheses
the primary key refers to column CustomerID, but there is no column in the table
Presumably, you meant:
create table HomeMortgageCompany (
HomeID INT,
CompanyID INT,
foreign key (CompanyID) references MortgageCompany(CompanyID),
foreign key (HomeID) references Home(HomeID),
Primary key (HomeID,CompanyID)
)

Related

How can I reference 2 different columns in 2 different tables simultaneously

This is an assignment and I have been given this diagram for reference - https://imgur.com/gallery/wRkArmQ
There are other tables that I will include but the issue seems to be with the tables section and time_slot. In the diagram, they reference each other but I don't know how to. Any comments are helpful! I am using Oracle btw, here is the code -
create table department (
dept_name varchar(15) primary key,
building varchar(10),
budget int
);
create table instructor (
id varchar(10) primary key,
name varchar(15) not null,
dept_name varchar(20) not null
references department(dept_name) on delete cascade,
salary int not null
);
create table course (
course_id varchar(10) primary key,
title varchar(10),
dept_name varchar(15)
references department(dept_name) on delete cascade,
credits int
);
create table classroom (
building varchar(10) not null,
room_no varchar(5) not null,
capacity int not null,
primary key (building, room_no)
);
create table section (
course_id varchar(10) not null
references course(course_id),
sec_id varchar(10) not null,
semester varchar(10) not null,
year varchar(10) not null,
building varchar(10) not null
references classroom(building),
room_no varchar(5) not null
references classroom(room_no),
time_slot_id varchar(5) not null
references time_slot(time_slot_id),
primary key (course_id, sec_id, semester, year)
);
create table time_slot (
time_slot_id varchar(5) not null
references section(time_slot_id),
day varchar(10) not null,
start_time date not null,
end_time date not null,
primary key (time_slot_id, day, start_time)
);
create table teaches (
id varchar(10) primary key
references instructor(id) on delete cascade,
course_id varchar(15) not null
references section(course_id),
sec_id varchar(5) not null
references section(sec_id),
semester varchar(15)
references section(semester),
year int not null
references section(year)
);
create table student (
id varchar(10) not null primary key,
name varchar(20) not null,
dept_name varchar(15) not null
references department(dept_name) on delete cascade,
tot_cred int not null
);
create table advisor (
s_id varchar(10) primary key
references student(id) on delete cascade,
i_id varchar(6)
references instructor(id) on delete cascade
);
create table prereq (
course_id varchar(10)
references course(course_id) on delete cascade,
prereq_id varchar(10)
references course(course_id) on delete cascade,
primary key (course_id, prereq_id)
);
create table takes (
id varchar(10) not null
references student(id) on delete cascade,
course_id varchar(10) not null
references section(course_id) on delete cascade,
sec_id varchar(10) not null
references section(sec_id) on delete cascade,
semester varchar(10) not null
references section(semester) on delete cascade,
year int not null
references section(year) on delete cascade,
grade varchar(10) not null,
primary key (id, course_id, sec_id, semester, year, grade)
);
This is the output -
Table created.
Table created.
Table created.
Table created.
ORA-02270: no matching unique or primary key for this column-list
ORA-00942: table or view does not exist
ORA-00942: table or view does not exist

Foreign key reference mismatched data type error

The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO

Can a non-primary key columns be referenced from a foreign key?

Here is table one I want to refer DesignationId to other table but it is not working
create table Employees
(
EmployeeID int identity(1,1) primary key,
EmployeeNumber int not null,
LocationID int not null,
EmployeeName varchar(20) not null,
DesignationID int not null,
CategoryID int not null,
)
Second table is that .. on third row it is showing error
create table Designation
(
DesignationID int primary key ,
JobTitle varchar(20) not null,
CONSTRAINT fk_Designation_Employees
FOREIGN KEY (DesignationID)
REFERENCES Employees (DesignationID),
)
You are creating this incorrectly. Try it this way instead:
create table Designation
(
DesignationID int primary key ,
JobTitle varchar(20) not null,
)
create table Employees
(
EmployeeID int identity(1,1) primary key,
EmployeeNumber int not null,
LocationID int not null,
EmployeeName varchar(20) not null,
DesignationID int not null,
CategoryID int not null,
CONSTRAINT fk_Employees_Designation
FOREIGN KEY (DesignationID)
REFERENCES Designation (DesignationID)
)
Many employees linked to a designation. One-To-Many relationship.

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.

Database schema for a school

Here is the database query needed to create the database:
create table Area
(
AreaId int primary key identity(1,1),
Name nvarchar(64) not null
)
create table Level
(
LevelId int primary key identity(1,1),
Name nvarchar(32) not null,
Principle nvarchar(512) not null
)
create table Subject
(
SubjectId int primary key identity(1,1),
AreaId int foreign key references Area(AreaId),
LevelId int foreign key references Level(LevelId),
Name nvarchar(32) not null,
Abbreviation nvarchar(16)
)
create table StaffType
(
StaffTypeId int primary key identity(1,1),
Name nvarchar(64) not null
)
create table Staff
(
StaffId int primary key identity(1,1),
StaffTypeId int foreign key references StaffType(StaffTypeId),
Name nvarchar(128) not null,
LastNameFather nvarchar(256) not null,
LastNameMother nvarchar(256) not null,
DateOfBirth datetime,
PlaceOfBirth nvarchar(256),
Sex nvarchar(8) not null,
Carnet nvarchar(64),
Telephone nvarchar(64),
MobilePhone nvarchar(64),
Address nvarchar(256),
FatherName nvarchar(256),
MotherName nvarchar(256),
FatherContactNumber nvarchar(64),
MotherContactNumber nvarchar(64),
FatherPlaceOfWork nvarchar(64),
MotherPlaceOfWork nvarchar(64),
DateOfHiring datetime,
YearsOfService int,
Formation nvarchar(128)
)
create table Grade
(
GradeId int primary key identity(1,1),
Name nvarchar(32) not null,
LevelId int foreign key references Level(LevelId),
Observation nvarchar(256)
)
create table GradeInstance
(
GradeInstanceId int primary key identity(1,1),
StaffId int foreign key references Staff(StaffId),
GradeId int foreign key references Grade(GradeId),
Name nvarchar(32) not null,
Year datetime
)
create table Student
(
StudentId int primary key identity(1,1),
RUDE int,
Name nvarchar(64) not null,
LastNameFather nvarchar(256) not null,
LastNameMother nvarchar(256) not null,
DateOfBirth datetime not null,
PlaceOfBirth nvarchar(128),
Sex nvarchar(8),
Carnet nvarchar(32),
Telephone nvarchar(64),
MobilePhone nvarchar(64),
Address nvarchar(256),
FatherName nvarchar(512),
MotherName nvarchar(512),
FatherMobilePhone nvarchar(64),
MotherMobilePhone nvarchar(64),
FatherProfession nvarchar(64),
MotherProfession nvarchar(64),
FatherPlaceOfWork nvarchar(256),
MotherPlaceOfWork nvarchar(256),
Observations nvarchar(3000)
)
create table StudentInstance
(
StudentInstanceId int primary key identity(1,1),
GradeInstanceId int foreign key references GradeInstance(GradeInstanceId),
StudentId int foreign key references Student(StudentId)
)
create table StudentGradeReport
(
StudentGradeReportId int primary key identity(1,1),
StudentInstanceId int foreign key references StudentInstance(StudentInstanceId),
SubjectId int foreign key references Subject(SubjectId),
FirstTrimester int,
SecondTrimester int,
ThirdTrimester int,
FinalGrade int
)
If you find an attribute that should be null checked, please disregard it. I've gone over this with the client and they want certain things to left blank if so chosen by the end user.
My main concern when designing this database was how to associate a student with a grade here and now, yet keep a record for previous years and manage to see what grade he got back in 2009. See?
I think I've done a good job but you never know - the hivemind here will probably find a flaw and I'd love some feedback.
No longer using SQLite, but MSSQL.
I've tried to normalize the database as much as I could, but not religiously, just as much as it took to make it 'click'.
Before a Student, was directly related to a Classroom (Grade) instance. Now I create 'instances' of Students and assign them to a Classroom (Grade) instance. Each instance has a date saying which year it belongs to. This helps me keep a record of previous years without dirty hacks.
create table Area
(
AreaId int primary key identity(1,1),
Name nvarchar(64) not null
)
"Name" should be UNIQUE.
create table Level
(
LevelId int primary key identity(1,1),
Name nvarchar(32) not null,
Principle nvarchar(512) not null
)
"Name" should be UNIQUE.
create table Subject
(
SubjectId int primary key identity(1,1),
AreaId int foreign key references Area(AreaId),
LevelId int foreign key references Level(LevelId),
Name nvarchar(32) not null,
Abbreviation nvarchar(16)
)
Odds are good that one or more of these apply. Impossible to tell without representative sample data.
The set {AreaId, LevelId} should be
UNIQUE.
"Name" should be UNIQUE.
"Abbreviation" should be UNIQUE.
I'm running out of time.
create table StaffType
(
StaffTypeId int primary key identity(1,1),
Name nvarchar(64) not null
)
"Name" should be UNIQUE.
More later if I have time.

Resources