我是否必须将外键声明为标识 [英] Do I have to declare a foreign key as identity

查看:95
本文介绍了我是否必须将外键声明为标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表的主键是一个标识。我将这个PK作为外键添加到另一个表中,但是如果我仍然需要将这个外键列设置为标识,那就徘徊了吗?



我有什么尝试过:



我已经看过在其他论坛中是否有必要但找不到答案。

I have one table that's primary key is an identity. I am adding this PK as a foreign key in a different table but wandered if i still had to set this foreign key column to identity?

What I have tried:

I have looked to see if this was necessary in other forums but cannot find an answer.

推荐答案

绝对不是!



1 - 外键用于一对多关系。它将父记录与任何数量的子记录联系在一起。

2 - 声明外键以防止任何记录在父表中没有引用(主键)的子表中。这有助于确保参照完整性。



如果您只需要为每个父记录强制执行一个子记录但仍保持外键约束,则为该记录添加UNIQUE约束。列,以及。




Absolutely NOT !

1 - The foreign key is used for a one-to-many relationship. It ties together a parent record with any amount of child records.
2 - The foreign key is declared to prevent any records from being in the child table that have no reference (primary key) in the parent table. This helps insure referential integrity.

If you need to force only a single child record for each parent record but still maintain the foreign key constraint the add a UNIQUE constraint to the column, as well.



同意Balboos。您的外键列必须与它在另一个表中引用的主键列具有相同的值。如果您的外键列是IDENTITY列,那么它将为每条记录创建新值。这些值不一定与您引用的主键列中的值匹配。这与创建外键的目的相矛盾。
Agree with Balboos. Your foreign key column must have the same value as the primary key column it's referencing in the other table. If your foreign key column were an IDENTITY column then it would be creating new values for every record. Those values would not necessarily match the values in the primary key column you're referencing. That would contradict the purpose of creating the foreign key.


这篇关于我是否必须将外键声明为标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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