Change a Nullable column to NOT NULL with Default Value

后端 未结 5 700
臣服心动
臣服心动 2021-02-02 05:17

I came across an old table today with a datetime column called \'Created\' which allows nulls. Now, I\'d want to change this so that it is NOT NULL, and also include a constrai

5条回答
  •  伪装坚强ぢ
    2021-02-02 05:34

    I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

    ALTER TABLE dbo.MyTable
    ADD CONSTRAINT my_Con DEFAULT GETDATE() for created
    
    UPDATE MyTable SET Created = GetDate() where Created IS NULL
    
    ALTER TABLE dbo.MyTable 
    ALTER COLUMN Created DATETIME NOT NULL 
    

提交回复
热议问题