Search code examples
database-designsql-server-2008-express

SQL Server 2008 Express - Got "The columns do not match an existing primary key or UNIQUE constraint" despite constraints being set


I have the following tables

ModuleClass ( <ModuleID>, <Section>, <Number>, StartDate, EndDate)
ClassEnrollment ( <ModuleID>, <Section>, <Term Code>, <User Name>, Role)

Now a ModuleClass entity can have more than one enrollment, so there is a 1 to M relationship. However, when attempting to define FK between ModuleClass and ClassEnrollment using ModuleID and Section, I get

The columns in table ClassEnrollment do not match an existing primary key or UNIQUE constraint

However, both ModuleID and Section are participating in a PK constraint.

(I am using the Visual Database Tools to create the tables and specify the relationship).

What is a better way of representing this relationship?


Solution

  • It looks like the primary key of ModuleClass is a composite key consisting of three columns, (ModuleID, Section, Number). To set a foreign key reference to that table, you'll have to target all three of those columns.

    To target all three of those columns, you'll need to include the column "Number" in the table ClassEnrollment. Then you can set

    FOREIGN KEY (ModuleID, Section, Number) 
      REFERENCES ModuleClass (ModuleID, Section, Number)