Baris
Baris

Reputation: 29

Create foreign key that references to composite key

CREATE TABLE Person
(
    PersonID int NOT NULL IDENTITY,
    PersonName nvarchar(30) NOT NULL,
    PersonSurname nvarchar(30) NOT NULL,
    PRIMARY KEY (PersonID)
)

CREATE TABLE Author
(
    AuthorID int NOT NULL IDENTITY,
    PersonID int NOT NULL,
    PRIMARY KEY (AuthorID),
    FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
)

CREATE TABLE Supervisor 
(
    SupervisorID int NOT NULL ,
    PersonID int NOT NULL,
    PRIMARY KEY (SupervisorID,PersonID),
    FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
)

CREATE TABLE University
(
    UniversityID int NOT NULL IDENTITY,
    UniversityName nvarchar(100) NOT NULL,
    PRIMARY KEY (UniversityID)
)

CREATE TABLE Enstitute
(
    EnstituteID int NOT NULL IDENTITY,
    UniversityID int NOT NULL,
    EnstituteName nvarchar(100),
    PRIMARY KEY (EnstituteID),
    FOREIGN KEY (UniversityID) REFERENCES University(UniversityID)
)

CREATE TABLE Thesis 
(
    ThesisNo numeric(8,0) NOT NULL IDENTITY,
    AuthorID int NOT NULL,
    EnstituteID int NOT NULL,
    SupervisorID int NOT NULL,
    Title nvarchar(100)NOT NULL,
    Abstract nvarchar(500)NOT NULL,
    Pages int NOT NULL,
    SubmitDate datetime NOT NULL,
    [Type] nchar(30) NOT NULL,
    [Language] nchar(20) NOT NULL
    PRIMARY KEY (ThesisNo),
    FOREIGN KEY (EnstituteID) REFERENCES Enstitute(EnstituteID),
    FOREIGN KEY (AuthorID) REFERENCES Author(AuthorID),
    FOREIGN KEY (SupervisorID) REFERENCES Supervisor(SupervisorID)
)

CREATE TABLE Keywords
(
    ThesisNo numeric(8,0) NOT NULL,
    Keyword nvarchar(50) NULL,
    FOREIGN KEY (ThesisNo) REFERENCES Thesis(ThesisNo)
)

CREATE TABLE Subjects
(
    SubjectID int NOT NULL,
    ThesisNo numeric(8,0) NOT NULL,
    [Subject] nvarchar(120) NOT NULL,
    PRIMARY KEY (SubjectID),
    FOREIGN KEY (ThesisNo) REFERENCES Thesis(ThesisNo) 
)

I get this error:

Msg 1767, Level 16, State 0, Line 38
Foreign key 'FK__Thesis__AuthorID__47DBAE45' references invalid table 'Author'.

Msg 1750, Level 16, State 1, Line 38
Could not create constraint or index. See previous errors

this is part of the diagram I want to do.

Upvotes: 0

Views: 500

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89479

Why does Supervisor have a compound key. It looks like a subtype of Person, and should share the same key structure. eg

CREATE TABLE Supervisor 
(
    PersonID int NOT NULL,
    PRIMARY KEY (PersonID),
    FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
)

Author too

CREATE TABLE Author
(
    PersonID int NOT NULL,
    PRIMARY KEY (PersonID ),
    FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
)

Although it's often better to just have a Person table.

Upvotes: 1

Related Questions