December 16, 2010

SQL Server Date Query

Here are some simple mssql queries if you need to change the current date in a query. That is if you need to find information in the past and don't want to hard code in values.

Yesterday:
SELECT GETDATE(), DATEADD(day, -1, GETDATE());

Seven Days ago:
SELECT GETDATE(), DATEADD(day, -7, GETDATE());

Last Year:
SELECT GETDATE(), DATEADD(year, -1, GETDATE());

Last Hour:
SELECT GETDATE(), DATEADD(hour, -1, GETDATE());

More specifically you would do something like this:

Show all sales within the past hour:
Select * from orders where
salesdate > DATEADD(hour, -1, GETDATE())

Comments

Add your Comments

Feel free to leave a comment about this post.

- Feel Free to add HTML to your comment!