Zombian
Zombian

Reputation: 1435

SQL Script Foreign Key Error

I am getting the error "Number of referencing columns in foreign key differs from number of referenced columns, table 'StudentGrade'" when trying to execute the following SQL script

CREATE TABLE StudentGrade

(

    StudentID INT NOT NULL
        CONSTRAINT FK_SG_StudentID FOREIGN KEY (StudentID)
        REFERENCES Student(StudentID),
    ClassID VARCHAR (6) NOT NULL
        CONSTRAINT FK_Class FOREIGN KEY (ClassID, CourseID)
        REFERENCES Class(ClassID),
    CourseID VARCHAR (64) NOT NULL
        CONSTRAINT FK_Course FOREIGN KEY (CourseID)
        REFERENCES Course(CourseID),
    FacultyID INT NOT NULL
        CONSTRAINT FK_Faculty FOREIGN KEY (FacultyID)
        REFERENCES Faculty(FacultyID),
    Grade NUMERIC NULL,
    CONSTRAINT PK_StudentID PRIMARY KEY (StudentID, ClassID, CourseID, FacultyID)

)

I know that there is something I am doing wrong with the foreign keys though I can't find anywhere where it explains how to use foreign keys and composite keys together. Any help would be greatly appreciated. Thank you so much!

Upvotes: 0

Views: 483

Answers (1)

Jose Rui Santos
Jose Rui Santos

Reputation: 15329

change your second foreign key from

CONSTRAINT FK_Class FOREIGN KEY (ClassID, CourseID)

to

CONSTRAINT FK_Class FOREIGN KEY (ClassID)

In FK_Class you are referencing the columns StudentGrade.ClassID and StudentGrade.CourseID into a single one Class.ClassID and this cannot work.

Your FK_Course already refers CourseID, so you can simply delete CourseID from FK_Class as I said above.

Edit

Add CourseID to your definition of FK_Class as

CONSTRAINT FK_Class FOREIGN KEY (ClassID, CourseID)
        REFERENCES Class(ClassID, CourseID)

Upvotes: 1

Related Questions