Can I add a not null column without DEFAULT value

后端 未结 10 1525
Happy的楠姐
Happy的楠姐 2020-12-13 07:56

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

10条回答
  •  爱一瞬间的悲伤
    2020-12-13 08:39

    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.

提交回复
热议问题