简体   繁体   中英

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_Gender has rows with values '1' and '2'

What will happen if I make default constraint in Table_Person for Gender column with default value = '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.

For SQL Server :

  • You can create both tables, including the default constraint in Table_Person

  • You can insert rows into Table_Person that explicitly define a value for Gender which is 1 or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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