Using DATEPART in sql statement to get records with specific year

821 views Asked by At

In Classic ASP:

I can extract the year from a date/time field:

tester=rs.fields("datestamp")
tester=DATEPART("yyyy",tester)

But I cannot seem to figure out how to make this work in a SQL statement to bring all the records from a specific year:

Select * from table1 where DATEPART("yyyy",datestamp)='2012'

and this doesn't work either:

Select * from table1 where DATEPART("yyyy",datestamp)=2012

I've looked through a zillion examples, here and elsewhere, and can't seem to find one that'll make this work. What am I doing wrong?

1

There are 1 answers

0
Mastercafe On

The function DatePart can extract from any date some values. The best explanation that i know is here: W3School.com

And this command can be used as a part of SQL string as you want, but in this case you must considerer that the main parameter change. Sample for filter by Month for less that June:

DATEPART(month, yourvar_withdate) <= 6

Check this explanation: W3School.com-SQL

Sure that you need use a number without quotes to eval. You can check "yy" or year (without quotes) to verify.

One more note, you must have always content on DateStamp field or receive an error.