简体   繁体   English

是否需要将外键设置为非null

[英]is it required to make foreign key as not null

Is it required to make foreign key column in a table as NOT NULL, If we not written explicitly foreign key column as not null what it will be? 是否需要将表中的外键列设置为NOT NULL,如果我们不将外键列显式地编写为非null,它将是什么? Can it contain null values? 可以包含空值吗?

And what is the Difference between following two statements: 以下两个语句之间有什么区别:

[PhoneId] [int] NOT NULL FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId)
[PhoneId] [int] FOREIGN KEY REFERENCES [dbo].[tbl_PhoneNumber](PhoneNumberId)

Is it required to make foreign key column in a table as NOT NULL, 是否需要将表中的外键列设置为NOT NULL,

No it is not required. 不,不是必需的。 MSDN says that:- MSDN说:

When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column; 当在FOREIGN KEY约束的列中输入非NULL的值时,该值必须存在于引用的列中; otherwise, a foreign key violation error message is returned. 否则,将返回外键冲突错误消息。 To make sure that all values of a composite foreign key constraint are verified, specify NOT NULL on all the participating columns. 要确保验证复合外键约束的所有值,请在所有参与列上指定NOT NULL。

So the simple answer to your question is NO IT IS NOT REQUIRED. 因此,您的问题的简单答案是不需要。

A foreign key attribute can contain NULL values as well. 外键属性也可以包含NULL值。

Your second definition will allow Nulls in the column. 您的第二个定义将允许Nulls列中。

From here :- 这里

When a FOREIGN KEY constraint is added to an existing column or columns in the table SQL Server, by default checks the existing data in the columns to ensure that all values, except NULL, exist in the column(s) of the referenced PRIMARY KEY or UNIQUE constraint. 当将FOREIGN KEY约束添加到表SQL Server中的一个或多个现有列时,默认情况下会检查这些列中的现有数据,以确保除NULL外的所有值都存在于引用的PRIMARY KEY的列中,或者唯一约束。

Also check Foreign Key Constraints 还要检查外键约束

根据sql规范化规则,外键值必须等于主键值或NULL,因此它将包含主键表行中一个值的NULL值。

It is not required. 不需要。 A foreign key attribute without NOT NULL can contain NULL values, and this can be used to indicate that no such tuple in the referenced relation is applicable. 没有NOT NULL外键属性可以包含NULL值,这可以用来指示在引用关系中没有这样的元组适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM