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?
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())
This should work in MySql
SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);
How about:
Select *
from some_table st
where st.month = to_char(sysdate,'MM') and
st.year = to_char(sysdate,'YYYY');
should work in Oracle. What database are you using? I ask because not all databases have the same date functions.
DECLARE @CMonth int=null
DECLARE @lCYear int=null
SET @lCYear=(SELECT DATEPART(YEAR,GETDATE()))
SET @CMonth=(SELECT DATEPART(MONTH,GETDATE()))
select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());
Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.
精彩评论