[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 107
  • Last Modified:

SQL cRetae table with Date Field that defaults to today's date

Hi

What SQL syntax would I use to create a table in SQL that has a Date Field that defaults to today's date when data is uploaded?
0
Murray Brown
Asked:
Murray Brown
  • 2
  • 2
2 Solutions
 
ste5anSenior DeveloperCommented:
CREATE TABLE YourTable
    (
      DateColumnWithDefault DATE NOT NULL
                                 CONSTRAINT DF_YourTable_DateColumnWithDefault DEFAULT ( GETDATE() ) ,
      Payload NVARCHAR(255)
    );

INSERT  INTO dbo.YourTable
        ( Payload )
VALUES  ( N'!' );

SELECT  *
FROM    dbo.YourTable YT;

DROP TABLE dbo.YourTable;

Open in new window

0
 
Scott PletcherSenior DBACommented:
The simplest syntax is just to add "DEFAULT GETDATE()" after the data type of the column:

CREATE TABLE tablename (
    id int,
    date_column datetime DEFAULT GETDATE(),
    ...
    )
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
thanks
0
 
ste5anSenior DeveloperCommented:
Please use always explicitly named constraints. Otherwise you'll have a hard time reading error messages. While this is not really a DEFAULT problem, it especially is created by the short

CREATE TABLE tablename
(
    id INT PRIMARY KEY
);

Open in new window


So, for symmetry or completeness reasons: Also name DEFAULT constraints.
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now