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

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

问题描述

我有两个表格

pre $ Table $(
FileID
undledFileID

  Table2(
FileID,
FileType,
FileName)

在Table2中, FileID FileType 是组合主键。我想创建一个从 Table1.FileID Table2 的外键关系。



是否可以这样做?

解决方案

一个复合主键(FileID,FileType),那么它的任何引用都必须包含两列

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

除非您在 Table2.FileID 字段(但是如果是的话:为什么这不是PK呢?),你不能创建一个FK关系到目标表上的PK部分 - 就是不能这样做。

I have two tables

Table1(
  FileID,
  BundledFileID,
  Domain)

and

Table2(
  FileID,
  FileType,
  FileName)

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

Is it possible to do this?

解决方案

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)

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天全站免登陆