SQL Server 2005 中与复合主键的外键关系 [英] Foreign key relationship with composite primary keys in SQL Server 2005

查看:24
本文介绍了SQL Server 2005 中与复合主键的外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子

Table1(
  FileID,
  BundledFileID,
  Domain)

Table2(
  FileID,
  FileType,
  FileName)

Table2 中的FileIDFileType 是复合主键.我想创建一个从 Table1.FileIDTable2 的外键关系.

In Table2 FileID and FileType are the composite primary key. I want to create a foreign key relationship from Table1.FileID to Table2.

可以这样做吗?

推荐答案

由于 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.

这篇关于SQL Server 2005 中与复合主键的外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆