简体   繁体   English

SQL:在外键引用不存在的外键列上添加默认约束

[英]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_PersonGender列作为外键
  • 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.

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