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

前端 未结 12 1668
离开以前
离开以前 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:49

    While the marked answer is correct with:

    ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

    You should always be aware of timezones when adding default datetime values in to a column.

    Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.

    If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:

    Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.

    ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn
    

    When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.

提交回复
热议问题