ShoeLace1291
ShoeLace1291

Reputation: 4698

Conflict with the foreign key constraint while populating a junction table in a M:N relationship

I have a M:N relationship between two tables called Students and Courses... this relationship is called Enrollment. I am using SQL Server management studio to populate the enrollment junction table with students who have enrolled in courses. I keep getting the error The INSERT statement conflicted with the FOREIGN KEY constraint "Enrolled In". The conflict occurred in database "midterm_project", table "dbo.Students", column 'studentId'. What does this mean?

Here is my query:

INSERT INTO [dbo].[Enrollment] (studentId, courseId, semesterId)
                        VALUES(1, 1, 4),
                              (2, 1, 4),
                              (3, 1, 4),
                              (4, 1, 4),
                              (5, 1, 4),
                              (6, 1, 4),
                              (7, 1, 4),
                              (8, 1, 4),
                              (9, 1, 4),
                              (10, 1, 4);

Here is my database model: enter image description here

Update:

I forgot that I had to delete my Students table and I created it but never populated the students table. So now I have populated the students table but I am now getting the error below when I populate the enrollment table using the same query above.

The INSERT statement conflicted with the FOREIGN KEY constraint "Has Scores". The conflict occurred in database "midterm_project", table "dbo.Assignments", column 'enrollmentId'.

What am I doing wrong?

Upvotes: 0

Views: 256

Answers (2)

Kason
Kason

Reputation: 797

As your enrollment table is weak entity of assignments, you cannot insert the records to enrollment before assignments. Based on your goals, the diagram I designed as below: enter image description here

You can insert a enrollment before insert assignmentsDetail(assignments). If you want one enrollment contains more than one assignment, you must have a id for identify ,as enrollmentId is not unique when you have more than one assignments.

Upvotes: 1

Charles Owen
Charles Owen

Reputation: 2890

Perhaps you're adding a studentid that doesn't exist in the Students table.

Upvotes: 0

Related Questions