Monday, February 16, 2009

MSSQL Searching for Datetime value

This is a great resource for trying to make a query in SQL Server for the datetime data type.  Use this if you're trying to find all entries from a date like yesterday, last month, or anything else.


What I found even more useful is this little code:

query = "SELECT * FROM your_table WHERE DATEDIFF(dd, your_date_field, GETDATE()) = 0"

What that does, is get you all entries from your_table where your_date_field and the current date (today's date) are not different.  The 'dd' means day, so it is comparing the day.

This will get all entries from yesterday:

query = "SELECT * FROM users WHERE DATEDIFF(dd, datecreated, GETDATE()) = 1"

And this will get from last week:

query = "SELECT * FROM users WHERE DATEDIFF(ww, datecreated, GETDATE()) = 1"

For a full list of what DATEDIFF does take a look at this: DATEDIFF (Transact-SQL)

Have fun!

No comments: