How to check a value from a nother table - sql-server

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

Related

WPF Cant insert into table - (I AM NOT SETTING VALUE INTO IDENTITY COULMN)

THIS IS NOT DUPLICITY
I am NOT setting value to identity column!
I cant add value in my Table. I think all set good but this error keeps comming:
"Cannot insert explicit value for identity column in table 'MainQueue'
when IDENTITY_INSERT is set to OFF."
My table:
CREATE TABLE [dbo].[MainQueue] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Created] DATETIME NOT NULL,
[IdOffice] INT NOT NULL,
[IdCategory] INT NOT NULL,
[StartProcessTime] DATETIME NULL,
[EndProcessTime] DATETIME NULL,
[IdUser] INT NULL,
[Sms] BIT CONSTRAINT [DF__MainQueue__Sms__412EB0B6] DEFAULT ((0)) NOT NULL,
[OrderNumber] INT NOT NULL,
[IdSms] INT NULL,
[UserWindowNumber] INT NULL,
CONSTRAINT [PK__MainQueu__3214EC0783954F32] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_MainQueue_Category] FOREIGN KEY ([IdCategory]) REFERENCES [dbo].[Category] ([Id]),
CONSTRAINT [FK_MainQueue_Office] FOREIGN KEY ([IdOffice]) REFERENCES [dbo].[Office] ([Id]),
CONSTRAINT [FK_MainQueue_User] FOREIGN KEY ([IdUser]) REFERENCES [dbo].[User] ([Id]),
CONSTRAINT [FK_MainQueue_SmsQueue] FOREIGN KEY ([IdSms]) REFERENCES [dbo].[SmsQueue] ([Id])
);
My code for adding:
var queueItem = new MainQueue();
queueItem.IdOffice = officeId;
queueItem.IdCategory = categoryId;
queueItem.Created = DateTime.Now;
queueItem.OrderNumber = orderNum;
dc.MainQueues.InsertOnSubmit(queueItem);
dc.SubmitChanges();
THIS IS NOT DUPLICITY
I am NOT setting value to identity column!
Your described ID column is an autoincrement identity column, that means you cannot pass any explicit value for the ID, after an insert the DBS will do fill the ID. Remove the ID column in your Insert method and do not pass a parameter for the Id when calling your method.
If you really need to insert an explicit value for the ID, either make the column not an IDENTITY, instead primary or turn IDENTITY INSERT OFF before you call the insert and turn in back on afterwards.

Create SQL Table with FK

I'm trying to create a table with a couple columns having the same FK constraint. What is wrong with my syntax? I'm receiving a msg 102, incorrect syntax error around "fk_fighterID"
"FIGHTERS" is a table that has been set up with "fighterID" as the primarykey
CREATE TABLE FIGHTS
(
FIGHTID INT PRIMARY KEY,
CONSTRAINT fk_fighterID FOREIGN KEY REFERENCES FIGHTERS(fighterID),
FIGHTER_ID_CHALLANGER int fk_fighterID,
FIGHTER_ID_CHALLANGED int fk_fighterID,
CONSTRAINT fk_weightclass FOREIGN KEY (classID) REFERENCES WEIGHT_CLASSES
(classID)
WEIGHTCLASS NOT NULL fk_wightclass,
IS_MAIN BIT NOT NULL,
IS_CO_MAIN BIT NOT NULL,
SCHEDULED ROUNDS TINYINT(1),
CONSTRAINT fk_WINMETH FOREIGN KEY (WINID) REFERENCES WINNING_METHODS (WINID)
WINNING METHOD NOT NULL fk_WINMETH
)
;
Correct Statement:
CONSTRAINT fk_weightclass FOREIGN KEY (classID) REFERENCES WEIGHT_CLASSES (classID)
Incorrect Statement:
CONSTRAINT fk_fighterID FOREIGN KEY REFERENCES FIGHTERS(fighterID),
You forgot to mention something like '(classId)'.
Edit:
I am not sure what you are trying to achieve, but your above query is wrong, try below query if it makes sense.
CREATE TABLE FIGHTS
(
FIGHTID INT PRIMARY KEY,
FIGHTER_ID_CHALLANGER INT,
FIGHTER_ID_CHALLANGED INT,
IS_MAIN BIT NOT NULL,
IS_CO_MAIN BIT NOT NULL,
SCHEDULED_ROUNDS TINYINT(1),
WEIGHTCLASS INT NOT NULL,
CLASS_ID INT NOT NULL,
WINNING_METHOD INT NOT NULL,
CONSTRAINT fk_fighterID FOREIGN KEY (FIGHTER_ID_CHALLANGER) REFERENCES FIGHTERS (fighterID),
CONSTRAINT fk_weightclass FOREIGN KEY (CLASS_ID) REFERENCES WEIGHT_CLASSES (classID),
CONSTRAINT fk_WINMETH FOREIGN KEY (WINNING_METHOD) REFERENCES WINNING_METHODS (WINID)
);
Shouldn`t the constraints be outside of the table creation statement like this:
CREATE TABLE Sales.TempSalesReason (TempID int NOT NULL, Name nvarchar(50),
CONSTRAINT PK_TempSales PRIMARY KEY NONCLUSTERED (TempID),
CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
REFERENCES Sales.SalesReason (SalesReasonID)
ON DELETE CASCADE
ON UPDATE CASCADE
);

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

Sql table shared for multiple 1-many relationships with delete cascade

I have a table that can be in a 1-* relationship with one of 2 different tables. I currently have it setup where there are 2 nullable columns that reference another table. However, this is causing an issue for cascade deletions.
CREATE TABLE [dbo].[TA] (
[Id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_TA] PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[TB] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TAId] INT NOT NULL,
CONSTRAINT [FK_TB_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[TC] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TAId] INT NULL,
[TBId] INT NULL,
CONSTRAINT [PK_TC] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_TC_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_TC_To_TB] FOREIGN KEY ([TBId]) REFERENCES [dbo].[TB] ([Id]), -- NOTE: DELETE CASCADE CAUSES A CIRCULAR REFERENCE
);
Essentially, this creates a nested structure like:
TA1
+ -- TC1, TC2
+ -- TB1
+ -- TC3, TC4
A TC object should only be a child of either TA or TB (not both). How should I go about developing this so that I can DELETE a TA row and have all TC and TB referenced rows deleted as well?
To resolve this I ended up breaking [TC] into multiple tables as described in a blog for entity framework. This created the following table structure:
CREATE TABLE [dbo].[TA] (
[Id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_TA] PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[TB] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TAId] INT NOT NULL,
CONSTRAINT [FK_TB_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[TCA] (
[Id] INT IDENTITY (2, 2) NOT NULL,
[TAId] INT NULL,
CONSTRAINT [PK_TCA] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_TCA_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
);
CREATE TABLE [dbo].[TCB] (
[Id] INT IDENTITY (1, 2) NOT NULL,
[TBId] INT NULL,
CONSTRAINT [PK_TCB] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_TCB_To_TB] FOREIGN KEY ([TBId]) REFERENCES [dbo].[TB] ([Id]) ON DELETE CASCADE,
);
I set the identities to even\odd values in order to prevent collision when creating a union of the two tables (see above link).

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