views:

61

answers:

5

I have a datetime field in my table. I want to delete records based on a date but I am not interested in the time element. How would I write the SQL for this ? I am using MS SQL 2008.

+3  A: 

For best use of indexes, I'd go for this kind of approach:

To delete all records for 1st December:

DECLARE @DateToDelete DATETIME
SET @DateToDelete = '20091201' 

DELETE FROM MyTable
WHERE MyDateField >= @DateToDelete AND MyDateField < DATEADD(dd, 1, @DateToDelete)

The alternatives include:

DELETE FROM MyTable
WHERE CAST(CONVERT(VARCHAR(10), MyDateField, 120) AS DATETIME) = @DateToDelete

which converts each datetime value to just it's date part.

But I'd still go with my original way as it allows for more efficient execution.

AdaTheDev
wouldn't you also delete records that were 20091202 00:00:00 using this approach?
Rippo
No, because I'm doing a < and not a <=
AdaTheDev
oops sorry! Missed that
Rippo
The 'alternative' is unsargable and won't use an existing index on the dat field.
Remus Rusanu
+1 - by "ignore the time element", what you *actually* mean in this context is all datetimes between e.g. 1 Dec 2009 00:00 and 1 Dec 2009 23:59, so the bounded constraint is definitely the clearest, and most efficient, way to do this.
Andrzej Doyle
A: 

Try this:-

declare @date datetime 
set @date = '2006-11-09'
select @date, dateadd(ms, -1, DATEADD(dd,1,@date))
delete from login 
where datecreated between @date AND dateadd(ms, -1, DATEADD(dd,1,@date))
Rippo
+1  A: 

If you use MS SQL 2008 then you could convert to a new DATE type

DELETE FROM table WHERE date_filed >= CONVERT(DATE,GETDATE())
Ilya Kochetov
A: 

This is what datediff is for:

delete from Table where datediff(day,'2009-12-09',date_filled) = 0
brianary
+1  A: 

Is the time relevant in any other place? If not, then you should use a DATE column instead. If you cannot, then the best way to seek a date part of a datetime in a WHERE clause is to use a range:

... WHERE dateColumn BETWEEN '20091221' and '20091222';

Note that given the datetime accuracy of 3ms a datetime like 20091221 23:59:59.999 may be aproximated to 20091222 00:00:00.000 and this can sometime create problems.

There is a great collection of blog posts on the topic of datetime at T-SQL Tuesday #001 (Date/Time Tricks): The Roundup

Remus Rusanu
The recommendation for using a DATE column only applies if the OP is on SQL Server 2008. SQL Server prior to 2008 only had datetime and smalldatetime. Also, the between clause given would match any records of time 00:00:00.000.
Shannon Severance
OP explicitly calls out it is on SQL 2008
Remus Rusanu
@Remus: You are correct. I missed that. I was just looking at the tags.
Shannon Severance