Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Current month/ year question

So I have a table that has the month and year broken down, for example field called Month has the number 7 in it (this month) and the Year field has 2011. Theres also additional months years, etc. How can I query this to show just the current year, month?

like image 999
GabrielVa Avatar asked Jul 13 '11 20:07

GabrielVa


People also ask

How do I get the current month in SQL Query?

We can retrieve the current month value in SQL using the MONTH() and DATEPART() functions along with the GETDATE() function. To retrieve the name of the month functions in SQL such as DATENAME() and FORMAT() are used.

How do I get current year in SQL?

Just run these SQL queries one by one to get the specific element of your current date/time: Current year: SELECT date_part('year', (SELECT current_timestamp));

How do you get the 15th of the current month in SQL?

Select Dateadd(d,1-DATEPART(d,getdate()),GETDATE()) as [First Day of the Month]; Changing this slightly yields the time preserved 15th day of the current month.


2 Answers

In SQL Server you can use YEAR, MONTH and DAY instead of DATEPART.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)

I prefer using these "short forms" because to me, YEAR(getdate()) is shorter to type and better to read than DATEPART(yyyy, getdate()).

So you could also query your table like this:

select * from your_table where month_column = MONTH(getdate()) and year_column = YEAR(getdate()) 
like image 179
Christian Specht Avatar answered Sep 22 '22 17:09

Christian Specht


This should work for SQL Server:

SELECT * FROM myTable WHERE month = DATEPART(m, GETDATE()) AND year = DATEPART(yyyy, GETDATE()) 
like image 39
Abe Miessler Avatar answered Sep 19 '22 17:09

Abe Miessler