gpt4 book ai didi

sql - 是否需要将外键设为非空

转载 作者:行者123 更新时间:2023-12-05 00:24:12 25 4
gpt4 key购买 nike

是否需要将表中的外键列设为 NOT NULL,
如果我们没有明确地将外键列写为非空,它将是什么?
它可以包含空值吗?

以及以下两个陈述之间的区别是什么:

[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,



不,这不是必需的。 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; 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.



因此,对您的问题的简单回答是不需要。

外键属性也可以包含 NULL 值。

您的第二个定义将允许 Nulls在列中。

来自 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 Constraints

关于sql - 是否需要将外键设为非空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19604852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com