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

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

    This works for me...

    ALTER TABLE [accounts] 
     ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
    
    0 讨论(0)
  • 2020-11-30 17:53

    In SQLPlus while creating a table it is be like as

    SQL> create table Test

     ( Test_ID number not null,
       Test_Date date default sysdate not null );
    

    SQL> insert into Test(id) values (1);

     Test_ID Test_Date
           1 08-MAR-19
    
    0 讨论(0)
  • 2020-11-30 17:57

    For modifying an existing column in an existing table:

    ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
    
    0 讨论(0)
  • 2020-11-30 17:58

    This also works:

    CREATE TABLE Example(
    ...
    created datetime default GETDATE()
    );
    

    Or:

    ALTER TABLE EXAMPLE ADD created datetime default GETDATE();
    
    0 讨论(0)
  • 2020-11-30 18:02

    This can also be done through the SSMS GUI.

    1. Put your table in design view (Right click on table in object explorer->Design)
    2. Add a column to the table (or click on the column you want to update if it already exists)
    3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

    0 讨论(0)
  • 2020-11-30 18:02

    In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP. The datatype of that column may be datetime or datetime2.

    e.g.

    Create Table Student
    (
      Name varchar(50),
      DateOfAddmission datetime default CURRENT_TIMESTAMP
    );
    
    0 讨论(0)
提交回复
热议问题