views:

67

answers:

1

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:

  1. 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.

  2. 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?

+3  A: 

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.

Kjetil Watnedal
:( I was so hoping there was a "cool" way to do it! But thank you for the information anyway... I will leave this post "unanswered" for a little while longer to see if there are any other thought provoking ideas.
Jimbo
+1, doesn't get any cooler than this!
KM
You could add the column with a default, then copy over the correct data, then drop the default constraint. Different path, same number of steps. I don't think it's going to get any "cooler".
mwigdahl