Solved

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

Posted on 2014-11-07
5
95 Views
Last Modified: 2014-11-08
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
Comment
Question by:murbro
  • 2
  • 2
5 Comments
 
LVL 32

Assisted Solution

by:Stefan Hoffmann
Stefan Hoffmann earned 250 total points
Comment Utility
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
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 250 total points
Comment Utility
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
 

Author Closing Comment

by:murbro
Comment Utility
thanks
0
 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
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
 

Author Comment

by:murbro
Comment Utility
Thanks
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now