I need to add a NOT NULL column to an existing (populated) table that will be a foreign key to another table. This brings about two problems:
When you add the column, its value cannot be null - using a default is not an option (unless it is removed later on) because the database logic is used in the server side validation when a user enters a new record i.e. when the application tries to add a record with this field having a null value, the database throws an error that the application catches and returns to the user, prompting them to correct it.
The column has a foreign key constraint, meaning its value MUST exist in the foreign table as well.
What is the best way to go about this?
Create the column, but allow NULL. Populate the column with the correct data from the foreign key table. Alter the column add not null. Add the foreign key constraint.
About parts of your questions (ofc after years):
1.If you mean that the default value would be something so smart, and you wouldn`t need to change it in future, then your wish is wrong. why?
for two reasons:
languages, DBs and so on...) the default value is not something which replace the value dynamically with something you want. For example Func Sum(a,b,c=10), in this situation if you don't enter parameter c, it would take it as 10, otherwise you should enter
something instead. so default values are predictable and calculable
values, NOT smart values.
parameter in a method, coz of the relational meanings in RDBMSs so u surely should edit that in future, even maybe sometimes it change
over and over base on usages of DB.
2.It can be handle with the code i`ll show you.
Therefore base on this explanations you could have a column with default value which exist in Fkeys, but it won`t be something you need, and you should update it in future base on your usage. and for this you need:
FIRST:
SECOND:
NOTE: As you know table and column names are sample.
THIRD:
All-in-One:
AND It`s Done!
Hope it solve your problem