Monday, March 12, 2012

Find records for X previous days

On a webform, I have three button ... [7 days] [15 days] [30 days]
When the user clicks one of the buttons, I want to return their orders for the past X days. The WHERE clause would include something like this (for 7 days):
WHERE (Order_Date BETWEEN CONVERT(DATETIME, GETDATE() - 7, 102) AND CONVERT(DATETIME, GETDATE(), 102))
How do I parameterize the number of days?
Thanks,
TimI dont think you can, so you will need to do:
WHERE (Order_Date BETWEEN CONVERT(DATETIME, GETDATE() - 7, 102) AND CONVERT(DATETIME, GETDATE(), 102) AND @.days = 7) OR (Order_Date BETWEEN CONVERT(DATETIME, GETDATE() - 15, 102) AND CONVERT(DATETIME, GETDATE(), 102) AND @.days = 15) OR (Order_Date BETWEEN CONVERT(DATETIME, GETDATE() - 30, 102) AND CONVERT(DATETIME, GETDATE(), 102) AND @.days = 30)

Nick|||

Try these links for CASE statement and SQL Server DATEDIFF function. Hope this helps.
http://www.craigsmullins.com/ssu_0899.htm

http://www.stanford.edu/~bsuter/sql-datecomputations.html

No comments:

Post a Comment