[英]SQL: add a default constraint on foreign key column where foreign key reference does not exist
What will happen if we try to add a default value constraint on a foreign key where that default value does not exist in the table ?如果我们尝试在表中不存在该默认值的外键上添加默认值约束,会发生什么?
Example:例子:
Table_Person
has Gender
column as foreign key Table_Person
有Gender
列作为外键Table_Gender
has rows with values '1' and '2' Table_Gender
具有值为“1”和“2”的行What will happen if I make default constraint in Table_Person
for Gender
column with default value = '3' ?如果我在
Table_Person
for Gender
列中使用默认值 = '3' 设置默认约束,会发生什么?
Will it be created or throw an error?它会被创建还是抛出错误? And reason for that?
原因是什么?
It will depend highly on what concrete database system (RDBMS) you're using.这在很大程度上取决于您使用的具体数据库系统 (RDBMS)。
For SQL Server :对于SQL 服务器:
You can create both tables, including the default constraint in Table_Person
您可以创建两个表,包括
Table_Person
中的默认约束
You can insert rows into Table_Person
that explicitly define a value for Gender
which is 1 or 2您可以将行插入到
Table_Person
中,明确定义Gender
的值为 1 或 2
You can not however insert rows into Table_Person
that omit the value for Gender
and thus would get the default value of 3 inserted - since that violates the FK constraint但是,您不能在
Table_Person
中插入省略Gender
值的行,因此会得到默认值 3 插入 - 因为这违反了 FK 约束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.