Skip to content
Advertisement

Add column to table with existing data in SQL Server

I have a table Rates with data in it and I need to add new column to the table however I get the error:

ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column ‘CreatedOn’ cannot be added to non-empty table ‘RateIncreases’ because it does not satisfy these conditions

How can I do this, I have disabled prevent saving changes that required table re-creation

Advertisement

Answer

What part of the error do you not understand? When a column is added to an existing table, there are rows. The column is assigned to each of those rows. SQL Server has to give those rows a value. How does it do this?

  • It can assign the default value for the column.
  • It can assign NULL.

In your case, you have defined the column as NOT NULL but not provided a default value. Hence, the database does not know what to do, so it returns an error.

The simplest solution is to remove the NOT NULL constraint in the definition. Very close behind is assigning a default value.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement