SQL脚本外键错误

时间:2011-06-07 06:00:21

标签: sql sql-server-2008 foreign-keys

我收到错误 “尝试执行以下SQL脚本时,外键中的引用列数与引用列数,表'StudentGrade'”不同

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)

)

我知道我的外键有问题,但我无法找到解释如何使用外键和复合键的地方。任何帮助将不胜感激。非常感谢你!

1 个答案:

答案 0 :(得分:1)

更改您的第二个外键
CONSTRAINT FK_Class FOREIGN KEY (ClassID, CourseID)

CONSTRAINT FK_Class FOREIGN KEY (ClassID)

FK_Class中,您将列StudentGrade.ClassIDStudentGrade.CourseID引用为一个Class.ClassID,但这不起作用。

您的FK_Course已提及CourseID,因此您只需按照上述说明从CourseID删除FK_Class

修改

CourseID添加到FK_Class的定义为

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