Can I add a not null column without DEFAULT value

Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:

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

If YES, please let me know the syntax, if No please specify the reason.


No, you can't.

Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.

The simplest way to do this is create the column with a default and then remove the default.

ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn

Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.


将该列添加到表中,更新现有行,以便它们都不为空,然后添加“非空”约束。


No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have

It's easy to create a DEFAULT at the same time, and then immediately drop it.

链接地址: http://www.djcxy.com/p/76274.html

上一篇: 可以列到SQL Server中的现有表?

下一篇: 我可以添加一个没有DEFAULT值的非空列