Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

SQL Select statement Where Month is current month and Year is current year

Hi

I have a Table called Table1, which has a field called "Year", containing  a string e.g. "2014"
and another column called Month containing e.g. "January" or "February"

I want to select all fields where the month is the current month and the year is the current year

What would the SQL statement be starting with "Select * From Table1 Where [Year] = "..............
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

SELECT *
FROM Table1
WHERE CAST(Year as int) = YEAR(GETDATE())  AND Month = DATENAME(MM, GETDATE())
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Murray Brown

ASKER

Thanks very much
If that string field [year] is already indexed,  casting YEAR(getdate())  to (n)varchar may be faster still
If it isn't indexed it may not make much difference either way

if [year] is varchar use varchar
if [year] is nvarchar use nvarchar

SELECT *
FROM Table1
WHERE [year] = cast( YEAR(getdate()) as varchar ) -- or nvarchar
AND [Month] = DATENAME(month,getdate()))


Personally I wouldn't store [year] as a string
and as an extra observation field names of [year] and [month] are not a great idea
Thanks for the help. Pity that I have already allocated points
no problem