Dates in SQL Server

By Bill Graziano on 1 August 2000 | 7 Comments | Tags: Queries


Assorted readers have written "Can i get system date in sql stmnts directly thru any function? and I want to take a date from the html form and wish to pass on to the stored procedure where the value is inserted

Let's start with the easiest one first. You can use the GETDATE() function to return the date and time of the server. For example,

SELECT Today=GETDATE()

returns

Today
---------------------------
2000-07-31 20:01:19.957


which is actually both the date and time. You can return just the date by using the formatting feature of the CONVERT function.

SELECT Today=convert(varchar, GETDATE(), 101)

returns

Today
------------------------------
07/31/2000


This converts the result of GETDATE to a VARCHAR and sets the style to 101. This happens to be the code for MM/DD/YYYY. There are numerous styles to choose from.

Inserting a date into a table using SQL shouldn't be very difficult. Converting from CHAR and VARCHAR to DATETIME is an implicit conversion that SQL Server should handle properly. If you are having problems I would make sure you have the date in one of the formats listed in the documentation for the CONVERT statement explicity convert it.

Insert MyTable(DateField)
Values ( convert (datetime, '3/15/2004'))


should get you a clean insert. Again, carefully check the format of the field you are trying to insert.

Discuss this article: 7 Comments so far. Print this Article.

If you like this article you can sign up for our weekly newsletter. There's an opt-out link at the bottom of each newsletter so it's easy to unsubscribe at any time.

Email Address:

Related Articles

Using Dynamic SQL in Stored Procedures (7 March 2011)

Joining to the Next Sequential Row (2 April 2008)

Writing Outer Joins in T-SQL (11 February 2008)

Aggregating Correlated Sub-Queries (23 October 2007)

How to Use GROUP BY with Distinct Aggregates and Derived tables (31 July 2007)

How to Use GROUP BY in SQL Server (30 July 2007)

Returning Complex Data from User-Defined Functions with CROSS APPLY (11 June 2007)

Returning a week number for any given date and starting fiscal month (2 May 2007)

Other Recent Forum Posts

Pulling daily data (0 Replies)

Clustered Index Scan Nightmare (2 Replies)

Comparision Operators (3 Replies)

Duplicate Data (1 Reply)

Help with string (2 Replies)

Alter column null and default value on existing (2 Replies)

Msg 8939, Level 16, State 98, Line 1 (2 Replies)

mdf files cleanup (4 Replies)

Subscribe to SQLTeam.com

Weekly SQL Server newsletter with articles, forum posts, and blog posts via email. Subscribers receive our white paper with performance tips for developers.

SQLTeam.com Articles via RSS

SQLTeam.com Weblog via RSS

- Advertisement -