The most efficient way, if there is an index on dtvisit1
is probably going to be:
WHERE dtvisit1 >= DATEDIFF(DAY, 0, dtvisit2)
AND dtvisit1 < DATEDIFF(DAY, -1, dtvisit2)
If there is an index on dtvisit2
then swap it around. This will still allow you to use an index on one side at least. If there is no index you can use other methods like converting to a string, though you run the risk of still requiring a full scan later even after you add an index to one or both columns. The convert to a string approach seems to be the knee-jerk reaction for most folks, however I demonstrate in this blog post why that is the last thing you want to do.
You might also consider adding a computed column, such as:
ALTER TABLE dbo.Visit
ADD visit1c AS (DATEDIFF(DAY, 0, dtvisit1));
ALTER TABLE dbo.Visit
ADD visit2c AS (DATEDIFF(DAY, 0, dtvisit2));
Then you could just say WHERE visit1c = visit2c
. Even simpler would be:
ALTER TABLE dbo.Visit
ADD visitc AS (DATEDIFF(DAY, dtvisit1, dtvisit2));
Then you could say WHERE visitc = 0
.
You may want to investigate persisting and/or indexing them.
In SQL Server 2008, you could simply convert both sides to DATE
, without losing sargability.