简体   繁体   中英

How to alter the table that can accept not null values

Can you please tell How to alter the table so that it can accept the not null constraint

alter table customer add emp_id int not null foreign key references emp(emp_id)

I have tried as above, but it is showing error:

Msg 4901, Level 16, State 1, Line 1

   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 'emp_id1' cannot be added to non-empty table 'customer' because it does not satisfy these conditions.

The error is pretty clear.

You are trying to add a non-null column to a table that has data. When you add the column, it has no value. So, the default value is put into the table for the existing rows. There is no default value, so NULL is used.

You can solve this in a few ways. One would be to empty the table truncate table customer , add the new column, then load the data again.

Another way would be to add the column with NULL allowed. Then fill in the value everywhere and then add the NOT NULL constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM