Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add non-nullable columns to an existing table in SQL server?

I already have a table which consists of data. I need to alter the table to add two new columns which are not null. How can I do that without losing any existing data?


Here's what I tried (via right-clicking the table and selecting Design):

  1. Added new columns 'EmpFlag' (bit, null), 'CreatedDate' (datetime, null)

  2. Updated 'EmpFlag' column in the table, to have some valid values. (Just wanted to work on one field, so I didn't update 'CreatedDate' field)

  3. Now right clicked table, design, and made it not null.

When I tried to save, this error message appeared:

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created.

like image 223
sanjeev40084 Avatar asked Feb 15 '10 19:02

sanjeev40084


People also ask

How do I add a NOT NULL column in SQL Server?

To enforce NOT NULL for a column in SQL Server, use the ALTER TABLE .. ALTER COLUMN command and restate the column definition, adding the NOT NULL attribute.

Can we add not null constraint existing table?

It is possible to add a NOT NULL constraint to an existing table by using the ALTER TABLE statement. In this case, the column_name must not contain any NULL value before applying the NOT NULL constraint.

How do I add a nullable column to an existing table in SQL?

ALTER TABLE SomeTable ADD SomeCol Bit NULL --Or NOT NULL. CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated. DEFAULT (0)--Optional Default-Constraint. WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.


1 Answers

You just set a default value in the new columns and that will allow you to add them.

alter table table_name     add column_name datetime not null        constraint DF_Default_Object_Name default (getdate()) 

or this one for a varchar field.

alter table table_name     add column_name varchar(10) not null        constraint DF_Default_Object_Name default ('A') 

You can also drop the default if you do not need it after you added the column.

alter table table_name     drop constraint DF_Default_Object_Name 
like image 192
Jose Chama Avatar answered Oct 10 '22 06:10

Jose Chama