foreign key references to a table problem here - sql-server

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.

Related

Associative table is erroring

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

Creting FOREIGN KEY constraint on multiple columns with one of them being constant value

When I have table with PRIMARY KEY from 2 columns:
CREATE TABLE SizeTypes
(
TypeID tinyint NOT NULL,
SizeID tinyint NOT NULL,
Name varchar(100) NOT NULL,
CONSTRAINT PK_SizeType
PRIMARY KEY (TypeID, SizeID)
)
How can I create second table with a foreign key that have 1st constant value and 2nd from column like below:
CREATE TABLE Something
(
ID INT IDENTITY(1,1) PRIMARY KEY,
SizeTypeID_1 TINYINT,
SizeTypeID_2 TINYINT,
SizeTypeID_3 TINYINT,
CONSTRAINT FK_Something_SizeTypes_1
FOREIGN KEY (1, SizeTypeID_1)
REFERENCES SizeTypes(TypeID, SizeID),
CONSTRAINT FK_Something_SizeTypes_2
FOREIGN KEY (2, SizeTypeID_2)
REFERENCES SizeTypes(TypeID, SizeID),
CONSTRAINT FK_Something_SizeTypes_3
FOREIGN KEY (3, SizeTypeID_3)
REFERENCES SizeTypes(TypeID, SizeID)
)
This can be done using FOREIGN KEY, if yes then how?
If no then what other ways to do this I have? Triggers on INSERT and UPDATE for table something and on DELETE for table SizeTypes? Any other choices I have?
It looks like the following code will let you create suitable check constraints with the check implemented by a separate function:
-- Create the first table.
create table SizeTypes(
TypeId TinyInt not NULL,
SizeId TinyInt not NULL,
Name VarChar(100) not NULL,
constraint PK_SizeType primary key ( TypeId, SizeId ) );
go
-- Create a function to implement the logic for the check constraint.
create function CheckSizeTypeId(
#TypeId TinyInt, #SizeId TinyInt )
returns Int
as begin
-- Replace the following statement with the logic for your check.
if #SizeId >= 0 and #SizeId <= ( select SizeId from SizeTypes where TypeID = #TypeID )
return 1;
return 0;
end;
go
-- Create the second table with the check constraints.
create table Something(
Id Int identity(1,1) primary key,
SizeTypeId_1 TinyInt,
SizeTypeId_2 TinyInt,
SizeTypeId_3 TinyInt,
constraint Check_SizeTypeId_1 check ( dbo.CheckSizeTypeId( 1, SizeTypeId_1 ) = 1 ),
constraint Check_SizeTypeId_2 check ( dbo.CheckSizeTypeId( 2, SizeTypeId_2 ) = 1 ),
constraint Check_SizeTypeId_3 check ( dbo.CheckSizeTypeId( 3, SizeTypeId_3 ) = 1 ) );
go
-- Houseclean.
drop table SizeTypes;
drop table Something;
drop function CheckSizeTypeId;
Note that the constraints restrict what you can do with values in Something. Changes in SizeTypes will not revalidate data in Something, though that could be implemented in a trigger on SizeTypes.

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

How to get a unique match pair from many tables?

I want to create a unique pair with one mentor and one mentee. I only want to have a mentor in only one pair and a mentee to belong to only one pair.
These are the tables that I have now involved in the pair:
create table member(
MemberID int not null primary key Identity (1,1),
MemberFName varchar(255),
MemberLName varchar(255),
MemberStreet varchar(255),
MemberCity varchar(255),
MemberState varchar(20),
MemberZip varchar(10),
MemberPhone bigint,
MemberEmail varchar(255),
MemberDOB date,
MemberGender char(1),
MemberChildren int,
MemberStartDate date,
CountryID int not null foreign key references country
) -- records all member information
create table mentor(
MentorID int not null primary key Identity (1,1),
MemberID int not null foreign key(MemberID) references member,
MentorOnlineSynch char(1),
MentorOnlineAsynch char(1),
MentorPhoneSkype char(1),
MentorFace char(1)
) -- mentor mentoring preferences
create table mentee(
MenteeID int not null primary key Identity (1,1),
MemberID int not null foreign key(MemberID) references member,
MenteeOnlineSynch char(1),
MenteeOnlineAsynch char(1),
MenteePhoneSkype char(1),
MenteeFace char(1)
) -- mentee mentoring preferences
create table pair(
PairID int not null primary key Identity (1,1),
MentorID int foreign key(MentorID) references mentor,
MenteeID int foreign key(MenteeID) references mentee,
PairStartDate date,
PairEndDate date
) -- pair details which include mentor and mentee id's and the date they were paired
This is what creates Pairs now; however, it allows mentors and mentees to be in multiple pairs:
insert into Pair (mentorid, menteeid, pair.pairstartdate)
select mentor.mentorid, mentee.menteeid, getdate()
from mentor, mentee
left join pair on pair.menteeid = mentee.menteeid
where mentor.menteeonlinesynch = 'Y'
and mentee.mentoronlinesynch ='Y'
and mentor.menteeonlinesynch = mentee.mentoronlinesynch
and mentor.memberid !=m entee.memberid
Any ideas on how to fix it to allow a mentor to be in only one pair and a mentee to be in only one pair?

Insert primary key identity(id) into other table as foreign key

I have two tables in SQL(InjuryScenario and ProductTypeDet)
CREATE TABLE InjuryScenario
(
InjuryScenario_id int identity(1,1),
InjuryScenario_name varchar(80),
InjuryDay int,
InjuryMonth int,
InjuryYear int,
InjuryDesc varchar(80),
InjuryComments varchar(50),
AlmostInjury int,
InjuryInSchool varchar(20),
ProductInjury varchar(20),
Cause_id int,
CauseType_id int,
CauseChar_id int,
Place_id int,
PlaceType_id int,
Username varchar(50),
InjuryDate_id int,
constraint pk_InjuryScenario_id primary key (InjuryScenario_id),
constraint fk_Cause_InjuryScenario foreign key(Cause_id) references Cause(Cause_id) on delete cascade,
constraint fk_CauseType_InjuryScenario foreign key(CauseType_id) references CauseType(CauseType_id) on delete no action,
constraint fk_Place_InjuryScenario foreign key(Place_id) references Place(Place_id) on delete cascade,
constraint fk_PlaceType_InjuryScenario foreign key(PlaceType_id) references PlaceType(PlaceType_id) on delete no action,
constraint fk_Users_InjuryScenario foreign key(Username) references Users(Username) on delete cascade,
constraint fk_InjuryDate_InjuryScenario foreign key(InjuryDate_id) references InjuryDate(InjuryDate_id) on delete cascade,
)
CREATE TABLE ProductTypeDet
(
ProductCategory_id int,
ProductType_id int,
Product_name varchar(80),
Brand_name varchar(80),
Notes varchar(80),
Manufacturer_name varchar(80),
Launch_Date date,
ProdTypeDesc varchar(80),
ProductInjury varchar(20),
Status_id int,
SafetyAct_id int,
InjuryScenario_id int foreign key references InjuryScenario(InjuryScenario_id),
constraint fk_ProductCategory_ProductTypeDet foreign key(ProductCategory_id) references ProductCategory(ProductCategory_id) on delete cascade,
constraint fk_ProductType_ProductTypeDet foreign key(ProductType_id) references ProductType(ProductType_id) on delete no action,
constraint fk_ProductStatus_ProductTypeDet foreign key(Status_id) references ProductStatus(Status_id) on delete cascade,
constraint fk_SafetyAct_ProductTypeDet foreign key(SafetyAct_id) references Product(SafetyAct_id) on delete no action
)
in VS i have Insert function that inserts data from the user to the tables.
i built SQL trigger-
CREATE TRIGGER tr_InjuryScenario_ForInsert
ON InjuryScenario
FOR INSERT
AS
BEGIN
DECLARE #Id int
SELECT #Id = InjuryScenario_id from inserted
INSERT INTO ProductTypeDet(InjuryScenario_id)
values(#Id)
END
i have a problem that in ProductTypeDet table two rows created- one from the trigger(just with the InjuryScenario_id and the other coloumns are null) and the other one from the Insert function in vs(coloumns filled from the user selections and the InjuryScenario_id is null).
how can i linked those 2 rows into one?
You never write a trigger like that! Inserted and deleted tables may contain multiple row and you tried to set the value to a scalar variable. (incidentally you should unit test triggers with multiple record inserts/updates or deletes) Use a set based propcess.
INSERT INTO ProductTypeDet(InjuryScenario_id)
SELECT InjuryScenario_id from inserted

Resources