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

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

Related

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.

on sql Foreign key

Can someone help me in SQL I'm using Oracle SQL*plus
Create the following tables.
Table Student:
stdNo CHAR(5) This is the Primary Key
lastname VARCHAR(25) Must be Not Null
givennames VARCHAR(50) Must be Not Null
Dept CHAR(4)
Table Course:
courseID CHAR(8) This is the Primary Key
courseTitle VARCHAR(50) Must be Unique and Not Null
Cost DECIMAL(6,2) Ensure Cost is greater or equal to zero
Credits INT Ensure that Credits are between 0 and 200. Also the default value is 2
Table Semester:
semesterID CHAR(5) This is the Primary Key
semesterCode INT Ensure that semesterCode is Between 1 and 4
Year INT Ensure that year is Between 2000 and 9999
Table Register:
stdNo CHAR(5) Foreign Key referenced to stdNo in Student table, On update cascade On delete cascade
courseID CHAR(8) Foreign Key referenced to courseID in Course table, On update cascade On delete cascade
semesterID CHAR(5) Foreign Key referenced to semesterID in Semester table, On update cascade On delete cascade
Grade CHAR(2)
Mark DECIMAL(4,2) Mark should be between 0.00 and 100.00
Primary Key (stdNo, courseID, semesterID)
Here in SQL (I'm using Oracle SQL*plus) .. table STD , SEMESTER works with me, but table COURSE I did not know how to put default value is 2 and table REGISTER dose not work with me at all :(
CREATE TABLE STD
(
STDNO CHAR(5) PRIMARY KEY,
LASTNAME VARCHAR(25) NOT NULL,
GIVENNAME VARCHAR(50) NOT NULL,
DEPT CHAR(4)
);
CREATE TABLE SEMESTER
(
SEMESTERID CHAR(5) PRIMARY KEY,
SEMESTERCODE INT CHECK(SEMESTERCODE BETWEEN 1 AND 4),
YEARS INT CHECK(YEARS BETWEEN 2000 AND 9999)
);
CREATE TABLE COURSE
(
COURSEID CHAR(8) PRIMARY KEY,
COURSETITLE VARCHAR(50) NOT NULL UNIQUE,
COST DECIMAL(6,2) CHECK(COST >= 0),
CREDITS INT CHECK(CREDITS BETWEEN 0 AND 200)
);
CREATE TABLE REGISTER
(
STDNO CHAR(5)
FOREIGN KEY REFERENCES STD(STDNO)
ON UPDATE CASCADE ON DELETE CASCADE,
COURSEID CHAR(5)
FOREIGN KEY REFERENCES COURSE(COURSEID)
ON UPDATE CASCADE ON DELETE CASCADE,
SEMESTERID CHAR(5)
FOREIGN KEY REFERENCES SEMESTER(SEMESTERID)
ON UPDATE CASCADE ON DELETE CASCADE,
GRADE CHAR(2),
MARK DECIMAL(4,2) CHECK(MARK BETWEEN 0.00 AND 100.0),
PRIMARYKEY(STDNO,COURSEID,SEMESTERID)
);
Please find below the solution.
COURSE - please use the below script to have a default value for CREDITS column
CREATE TABLE COURSE
(
COURSEID CHAR(8) PRIMARY KEY,
COURSETITLE VARCHAR(50) NOT NULL UNIQUE,
COST DECIMAL(6,2) CHECK(COST >= 0),
CREDITS INT DEFAULT 2 CHECK(CREDITS BETWEEN 0 AND 200)
);
REGISTER - Oracle Does not allow a Foreign Key Constraint with "ON UPDATE CASCADE". So you will have to use triggers for the same. Find below the scripts that you could make use of,
CREATE TABLE REGISTER
(
STDNO CHAR(5),
COURSEID CHAR(8), -- UPDATED THE DATATYPE TO SAME AS MASTER TABLE
SEMESTERID CHAR(5),
GRADE CHAR(2),
MARK DECIMAL(4,2) CHECK(MARK BETWEEN 0.00 AND 100.0),
CONSTRAINT register_pk PRIMARY KEY(STDNO,COURSEID,SEMESTERID),
CONSTRAINT register_fk1 FOREIGN KEY (STDNO) REFERENCES STD(STDNO)
ON DELETE CASCADE,
CONSTRAINT register_fk2 FOREIGN KEY (COURSEID) REFERENCES COURSE(COURSEID)
ON DELETE CASCADE,
CONSTRAINT register_fk3 FOREIGN KEY (SEMESTERID) REFERENCES SEMESTER(SEMESTERID)
ON DELETE CASCADE
);
CREATE OR REPLACE TRIGGER cascade_stdno_update
AFTER UPDATE OF stdno ON std
FOR EACH ROW
BEGIN
UPDATE REGISTER
SET stdno = :NEW.stdno
WHERE stdno = :OLD.stdno;
END;
/
CREATE OR REPLACE TRIGGER cascade_courseid_update
AFTER UPDATE OF courseid ON course
FOR EACH ROW
BEGIN
UPDATE REGISTER
SET courseid = :NEW.courseid
WHERE courseid = :OLD.courseid;
END;
/
CREATE OR REPLACE TRIGGER cascade_semesterid_update
AFTER UPDATE OF semesterid ON semester
FOR EACH ROW
BEGIN
UPDATE REGISTER
SET semesterid = :NEW.semesterid
WHERE semesterid = :OLD.semesterid;
END;
/

How to check a value from a nother table

I have Table:
create table Authorized(
diver_number int not null,
level_name char(30) not null,
constraint PK_Authorized primary key (diver_number, level_name),
Constraint FK_diver_number1 foreign key (diver_number) references Diver(diver_number)
on update cascade on delete cascade,
Constraint FK_level_name foreign key (level_name) references Level(name)on update
cascade on delete cascade,
club_number int Constraint FK_club_number foreign key (club_number) references DivingClub(number)
on update cascade on delete cascade not null,
authorization_date date not null,
picture image)
And atable:
create table Works_for(
diver_number int not null,
club_number int not null,
constraint PK_Works_for primary key (diver_number, club_number),
Constraint FK_diver_number2 foreign key (diver_number) references Diver(diver_number)
on update cascade on delete cascade ,
Constraint FK_club_number2 foreign key (club_number) references DivingClub (number)on update
cascade on delete cascade,
start_working_date date not null,
end_working_date date)
When i add diver_number to table Works_for, i want to check if this diver is a "Guide" (level_name in Authorized table). How can i check it?
I would think your scalar function would be more like this.
CREATE FUNCTION dbo.checkADate(#diver_number int) RETURNS BIT AS
BEGIN
declare #Found bit
select #Found = count(*)
from Authorized
WHERE diver_number = #diver_number
and level_name = 'Guide'
return #Found
END

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