我已经有一个包含数据的表格。我需要更改表以添加两个不为空的新列。我怎样才能在不丢失任何现有数据的情况下做到这一点?
这是我尝试过的方法(通过右键单击表格并选择“设计”):
添加了新列“EmpFlag”(位、空)、“CreatedDate”(日期时间、 空)
更新了表中的“EmpFlag”列,使其具有一些有效值。 (只是想在一个字段上工作,所以我没有更新'CreatedDate'字段)
现在右键单击表格,设计,并使其不为空。
当我尝试保存时,出现了这个错误信息:
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created.
最佳答案
您只需在新列中设置默认值即可添加它们。
alter table table_name
add column_name datetime not null
constraint DF_Default_Object_Name default (getdate())
或者这个用于 varchar 字段。
alter table table_name
add column_name varchar(10) not null
constraint DF_Default_Object_Name default ('A')
如果在添加列后不需要默认值,您也可以删除它。
alter table table_name
drop constraint DF_Default_Object_Name
关于sql - 将不可空列添加到 SQL Server 中的现有表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2268513/