Transact SQL Other Articles Software Reviews
SQL Server Help: Using Microsoft's Transact SQL DatePart function
Getting the current date (and time) in SQL Server's SQL is possible by using the GetDate function. This can be used to show the current date:
SELECT GetDate() AS 'CurrentDate'
The GetDate function can also be used to assign the current date to a datetime variable, as shown in the following example:
DECLARE @TodaysDate DATETIME
The GetDate function returns the current entire date and time. To just retrieve the year, month, week or time period it is possible to use the DatePart function, passing in the date variable as a parameter (the date can also come from a database datetime or smalldatetime field.
The DatePart function takes two arguments, a date part, plus a date variable (which can be either a datetime or smalldatetime). The first argument, the date part, can be one of the following abbreviations:
The date part does not need to be enclosed in quotes.
In the example below, the SQL statement is used to find orders where the ShippedDate year was 2008:
SELECT * FROM Orders WHERE DATEPART(yy, ShippedDate) = 2008
Note that Transact SQL has a few shortcuts that can be used instead of DatePart: