1
votes

so i was working on my project then i was trying to insert some values that are foreign keys

The INSERT statement conflicted with the FOREIGN KEY constraint "SCHEDFK4". The conflict occurred in database "EnrollmentDatabase", table "dbo.tblSubject", column 'Subject_ID'.

Here are my SQL entities

CREATE TABLE tblGradeLevel
(
     Grade_ID VARCHAR   (5) NOT NULL,
     Grade_Name VARCHAR (20)  NULL, 
     PRIMARY KEY (Grade_ID)
)

CREATE TABLE tblSubject
(
    Subject_ID VARCHAR (5)NOT NULL,
    Subject_Name VARCHAR (20) NOT NULL,
    Subject_Desc VARCHAR (20) NOT NULL,
    Grade_Name VARCHAR   (5) NOT NULL,
    PRIMARY KEY (Subject_ID), 
    CONSTRAINT SUBFK1 FOREIGN KEY (Grade_ID) 
        REFERENCES tblGradeLevel (Grade_ID)
)

CREATE TABLE tblSchedule
(
     Subject_Schedule_ID VARCHAR (5)NOT NULL,
     Section_ID VARCHAR (5)NOT NULL,
     Teacher_ID VARCHAR (5)NOT NULL,
     Time_In VARCHAR (20)NOT NULL, 
     Time_Out VARCHAR (20)NOT NULL, 
     Subject_ID VARCHAR (5)NOT NULL,
     Grade_ID VARCHAR (5)NOT NULL,

     PRIMARY KEY (Subject_Schedule_ID), 
     CONSTRAINT SCHEDFK1 FOREIGN KEY (Student_ID) 
         REFERENCES tblStudent_Information (Student_ID),
     CONSTRAINT SCHEDFK2 FOREIGN KEY (Section_ID) 
         REFERENCES tblSection (Section_ID),
     CONSTRAINT SCHEDFK3 FOREIGN KEY (Teacher_ID) 
         REFERENCES tblTeacher (Teacher_ID),
     CONSTRAINT SCHEDFK4 FOREIGN KEY (Subject_ID) 
         REFERENCES tblSubject (Subject_ID),
     CONSTRAINT SCHEDFK5 FOREIGN KEY (Grade_ID) 
         REFERENCES tblGradeLevel (Grade_ID)
 ) 
2
Check your value in dbo.tblsubject . I think foreign key value (subjectid) is not present in dbo.tblsubject that's why an error has occurred. - MUHAMMAD TASADDUQ ALI

2 Answers

0
votes

This is very easy to understand from your error that you are trying to insert a record in tblSchedule but corresponding Subject_ID is missing in tblsubject table.

You have two options to fix this problem.

  1. Drop the foreign key constraint.
  2. Insert into tblsubject an entry which you need to refer in tblSchedule table.

You can read more about Foreign Key Constraints at MSDN link here.

0
votes

To avoid this error from happening, make sure that the value you are inserting into a column that references another table exists in that table. If the value does not exist in the primary table, insert to that table first before doing the insert on the second table.

To avoid this error, insert into the [dbo].[tblsubject] table first before inserting to the [dbo].[tblSchedule] table.