且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2005 中与复合主键的外键关系

更新时间:2023-02-02 23:02:54

由于 Table2 有一个复合主键 (FileID, FileType),那么对它的任何引用也必须包含 两列.

Since Table2 has a composite primary key (FileID, FileType), then any reference to it must also include both columns.

ALTER TABLE dbo.Table1
  ADD CONSTRAINT FK_Table1_Table2
  FOREIGN KEY(FileID, FileType) REFERENCES Table2(FileID, FileType)

除非您在 Table2.FileID 字段上有一个唯一的约束/索引(但如果是这样:为什么这不是 PK??),您不能只与部分目标表上的 PK - 就是做不到.

Unless you have a unique constraint/index on the Table2.FileID field (but if so: why isn't this the PK??), you cannot create a FK relationship to only parts of the PK on the target table - just can't do it.