views:

497

answers:

8

I have a database with event information, including date (in MMDDYYYY format). is it possible to write an SQL Server statement to only get rows that fall within a certain time frame?

something like this pseudo-statement:

SELECT * FROM events WHERE [current_date minus date <= 31] ORDER BY date ASC

where date is the date in the SQL Server row and current_date is today's date. The 31 is days, so basically a month's time.

I can easily process the data after a generic statement (read: SELECT * FROM events ORDER BY date ASC), but it would be "cool" (as in me learning something new :P) to know if this is possible.

A: 

DateDiff and GetDate() should sort you out.

Example:

SELECT * FROM events WHERE DATEDIFF(day, date, GETDATE()) <= 31 ORDER BY date ASC
Steven Robbins
won't perform since you are using functions WHERE date > getdate() - 31 is much better
SQLMenace
Avoid getdate() in where clauses when possible, as it results in a non-deterministic query.
geofftnz
+2  A: 

Use DateDiff:

SELECT * FROM events WHERE DATEDIFF(day, date, getdate()) < 31 ORDER BY date ASC

http://msdn.microsoft.com/en-us/library/ms189794.aspx

Troy
won't perform well since you are using functions WHERE date > getdate() - 31 is much better
SQLMenace
+3  A: 

SELECT * FROM events WHERE date > getdate() - 31 ORDER BY date ASC

Gordon Bell
I get an arithmetic overflow error when converting my date column (string, in the format of mmddyyyy) to timestamp. is there a function i can call such as a CType(date,datetime)?
Anders
Try: convert(datetime, substring(date, 5, 4) + '-' + substring(date, 1, 2) + '-' + substring(date, 3, 2))
Gordon Bell
A: 

You could probably use the DATEDIFF function.

D'oh, Ninja'd while looking it up to make sure I wasn't speaking nonsense! :)

Wayne M
A: 

Also:

SELECT * 
FROM events 
WHERE current_date BETWEEN dateadd(day,-31,getdate()) AND getdate() 
ORDER BY date ASC

Although really BETWEEN is an abomination

David
A: 

Use GetDate() to return the current date.

Add or subtract in days.

An example would be:

SELECT *
FROM MY_TABLE T
WHERE T.SOME_DATE BETWEEN (GetDate()-31) AND GetDate()
JosephStyons
+2  A: 
DECLARE @start_date datetime
SET @start_date = DATEADD(day, -31, getdate())
SELECT * FROM events WHERE date BETWEEN @start_date AND getdate()
Dave Swersky
+1  A: 

For best performance, don't use a function in the expression. First calculate the threshold date (in your client or a stored procedure) and then use

SELECT ... WHERE [date] > {put threshold here}

le dorfier