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

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

    Let's say you create a database table for a registration system.

    IF OBJECT_ID('dbo.registration_demo', 'U') IS NOT NULL 
      DROP TABLE dbo.registration_demo; 
    
    CREATE TABLE dbo.registration_demo (
        id INT IDENTITY PRIMARY KEY,
        name NVARCHAR(8)
    );
    

    Now a couple people register.

    INSERT INTO dbo.registration_demo (name) VALUES
        ('John'),('Jane'),('Jeff');
    

    Then you realize you need a timestamp for when they registered.

    If this app is limited to a geographically localized region, then you can use the local server time with GETDATE(). Otherwise you should heed Tanner's consideration for the global audience with GETUTCDATE() for the default value.

    Add the column with a default value in one statement like this answer.

    ALTER TABLE dbo.registration_demo
    ADD time_registered DATETIME DEFAULT GETUTCDATE();
    

    Let's get another registrant and see what the data looks like.

    INSERT INTO dbo.registration_demo (name) VALUES
        ('Julia');
    
    SELECT * FROM dbo.registration_demo;
    
    id    name    time_registered
    1     John    NULL
    2     Jane    NULL
    3     Jeff    NULL
    4     Julia   2016-06-21 14:32:57.767
    

提交回复
热议问题