Brettb.Com
  HOME | ABOUT ME | BIOTECHNOLOGY | ARTICLES | GALLERY | CONTACT
Search: Go
TECHNICAL ARTICLES
 ASP
 ASP.NET
 JavaScript
 Transact SQL
 Other Articles
 Software Reviews

PHOTO GALLERIES
 Canon EOS 300D Samples
 Akihabara Maids!
 More Galleries...

TRAVEL LOG
 2009: China
 2008: Tokyo
 2007: Tokyo
 2006: Hong Kong
 2005: New York City

MORE STUFF
 Search Engine Optimisation
 Build an ASP Search Engine
 My Tropical Fishtank
 Autoglass
 SQL Month Name
 SQL Get Date Today
 SQL Year Month
 Other New Stuff...

POPULAR STUFF
 Regular Expressions
 Index Server & ASP
 JavaScript Ad Rotator

Home > Articles > Transact SQL Programming Articles

SQL Server Help: How to find the Year and Month in Transact-SQL

To get a variable with today's date you can use the SQL GetDate() function. This function returns a DateTime variable which can be used in other date functions.

DECLARE @TodayDate DateTime
SELECT @TodayDate = GetDate()

In this example the @TodayDate variable will contain both the current date and time. Usually in SQL it is useful to get parts of the date, like the Year or the Month.

There is a SQL function called Year, this returns the Year of any DateTime date type supplied as the Year function's argument:

SELECT YEAR(@TodayDate)

or

SELECT YEAR(GetDate())

Similarly, the SQL Month function will return the month's number (1 for January and 12 for December):

SELECT MONTH(@TodayDate)

Since this will just return a number, it isn't always useful for when displaying the date to end users of the database SQL query. To display the month's name then you can use the DateName function:

SELECT DateName(mm, @TodayDate) AS 'month'

This will return an nvarchar variable with the month name (i.e. 'January' .... 'December').

More SQL Resources

  • The SQL Documentation Tool builds technical documentation for Microsoft SQL Server databases. A free trial version is available for download.

  Site Map | Privacy Policy

All content is 1995 - 2012