How do I compare two datetime fields in SQL Server 2005?

DECLARE  @p_date DATETIME
SET      @p_date = CONVERT( DATETIME, '14 AUG 2008 10:45:30',?)

SELECT   *
FROM     table1
WHERE    column_datetime = @p_date

      

I need to compare a date, for example:

@p_date=14 AUG 2008 10:45:30
column_datetime=14 AUG 2008 10:45:30

      

How can i do this?

+1


source to share


2 answers


The question is unclear, but it looks like you are trying to do an equality match that does not return the expected rows, so I guess the problem is that milliseconds are problematic. There are several approaches here:

  • format both values ​​(as varchar, etc.) using CONVERT: expensive CPU, can't use index
  • use DATEDIFF / DATEPART to do the math - similar but not quite that expensive
  • create a search range between

The third option is almost always the most efficient because it can use indexing efficiently and does not require CPU mass.

For example, in the example above, since your precision is seconds *, I would use:

DECLARE @end datetime
SET @end = DATEADD(ss,1,@p_date)

      



then add the WHERE of the form:

WHERE column_datetime >= @p_date AND column_datetime < @end

      

This will work best if you have a clustered pointer to column_datetime, but it will still work fine if you have a nonclustered index on column_datetime.

[* = if @p_date includes milliseconds, you need to think more about whether to trim those milliseconds after DATEADD

or make a smaller range, etc.]

+1


source


I don't quite understand your problem, but DateDiff can be used to compare dates.



0


source







All Articles