I already have a table which consists of data. I need to alter table to add two new columns which are not null. How can i do that without loosing any existing data?
NOTE: The new columns are not null fields.
I already have a table which consists of data. I need to alter table to add two new columns which are not null. How can i do that without loosing any existing data?
NOTE: The new columns are not null fields.
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
If you don't want to place a default on the columns, you can:
Alrite this is what i did.
Right click table and clicked on 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 tried to save, this error message apeared:
"Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. ......."
Any suggestion?