In MSSQL, how do I add a column to a table of type "not null", if there is existing data in the table?

StackOverflow https://stackoverflow.com/questions/23610369

  •  20-07-2023
  •  | 
  •  

Question

If I attempt this in Microsoft SQL Server Management Studio, it gives an error if there is existing data in the table:

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

enter image description here

Is it possible to do this manually without dropping the table?

Était-ce utile?

La solution

If all rows are going to receive the same non-NULL value for this new column, then you can add the non-NULL column with a default constraint:

alter table T add NewColumn int not null constraint DF_T_NewColumn DEFAULT 1

It's then up to you whether you wish to leave this default constraint in place or to remove it now that the column has been populated:

alter table T drop constraint DF_T_NewColumn

The alternative (presented in your answer) may be more appropriate if you want to compute different values for each row, but you should be aware that it will have to scan the entire table at least twice during your 3 steps - once to set the new values and then again in order to verify that they're all non-NULL when changing the nullability of the column.

Autres conseils

You can add a column in SSMS if you add the column at the end of the table definition. If you add the column between existing columns, SQL has to do a lot "under the hood" to get that column order: create a new table, copy all the data, drop the original table, then rename the new table. If you have a large data with a lot of data, it can take a long time (and SSMS can time out).

One method is to do it manually.

Step 1: add the column, and let it be "null" (don't worry, we'll change this later).

ALTER TABLE [dbo].[MyTable] ADD MyColumnName int NULL 

Step 2: update the contents of the column to a default:

UPDATE [dbo].[MyTable] SET MyColumn=1 where MyColumnName is NULL

Step 3: Set the column so its "not null" (this passes now, as there is no null items in the column):

ALTER TABLE [dbo].[MyTable] ALTER COLUMN MyColumn int NOT NULL
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top