Add default value of datetime field in SQL Server to a timestamp

前端 未结 12 1642
离开以前
离开以前 2020-11-30 17:20

I\'ve got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn\'t put a timestamp in the table. I want it to e

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 17:41

    Disallow Nulls on the column and set a default on the column of getdate()

    /*Deal with any existing NULLs*/
    UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value 
                                                    '19000101' maybe?*/
    WHERE created_date IS NULL
    
    
    /*Disallow NULLs*/
    ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL
    
    /*Add default constraint*/
    ALTER TABLE YourTable ADD CONSTRAINT
        DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
    

提交回复
热议问题