Search code examples
sqlsql-serversql-server-2005t-sql

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.


Solution

  • 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.