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?
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.
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));
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.
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())
This should work for SQL Server:
SELECT * FROM myTable WHERE month = DATEPART(m, GETDATE()) AND year = DATEPART(yyyy, GETDATE())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With