I am building a dynamic query as a stored procedure in SQL Server 2008 and I'm getting some unexpected results when I compare a date (supplied as a parameter) and a datetime (stored in the database). I searched around for some ways to compare the two without taking the time portion into consideration and found this:
DATEDIFF(day, @d, v.ScheduledDate) = 0
What I'm doing with this is trying to find records where the supplied date parameter and the stored ScheduledDate are the same (in terms of days, e.g. 02/05/2011 and 02/05/2011 11:26:19.157). This is query that I wrote to do this:
SET @sql = 'SELECT e.Id, e.FirstName, e.LastName, v.ScheduledDate
FROM Employee e, Visit v
WHERE 1=1'
-- Several IF IS NOT NULL statements here
IF @d IS NOT NULL
BEGIN
SET @sql = @sql + ' AND DATEDIFF(day, ''' + @d + ''',' + 'v.ScheduledDate) = 0
AND v.EmpId = e.Id '
END
EXEC (@sql)
I would expect that this query would result in the all of the ScheduledDates for any employee who has a visit scheduled for that day. In other words, if I have two employees with Ids 5 and 7, and there exists in the Visit table two ScheduleDate entries on 02/05/2011 for employees with Ids 5 and 7, I would expect to get both those employees back when I run this query. It seems, however, that when I run it, I only get one row back. (As a side note, the two ScheduledDate entries I'm working with are on the same day, but about 3 hours apart from each other. I would think that the DATEDIFF function would account for this, since a few hours is certainly within the time frame of a day.) If I change the = in the query to a >= 0 or a <= 0, I get more rows as expected, but oddly enough still only get the single entry for that specific date. There are other records in the table where the same Employee has multiple visits on different dates, and those are returned accordingly when I use >= 0 or <= 0. For example, Employee with Id 41 has 3 visits on 10-29-2011, 11-24-2011, and 12-28-2011 and all 3 of those are returned when I change DATEDIFF to >= 0. I'm still confused as to why I'm only getting back the single record when two different Employees have a visit scheduled on the same date. Could anyone provide some insight as to where my logic is going wrong here? Note that when I'm testing this, I'm only supplying the ScheduledDate parameter. All of the other IF IS NOT NULL statements just fall through since all other params are inserted as NULL.