January 25, 2006 at 5:15 am
Hi,
I need to join two tables using datetime fields, but i only want to join using the date part dd/mm/yyyy. In otherwords I want to ignore times, so that 01/01/2001 nn:nn:nn = 01/01/2001 nn:nn:nn where n is any time.
I have written a select statement which joins by using the convert function to convert both datetimes to a varchar(10) dd/mm/yyyy. I know this is a terrible way to join tables but I have no other choice at this stage. As you would guess the select is very slow as I cannot use an index for the convert expression.
Is there a better way I can join these tables on date, hopefully using indexes??
Thanks!
January 25, 2006 at 5:31 am
not sure this will be better than convert(), but can give it a try
select dateadd(day, 0, datediff(day, 0, getdate()))
January 25, 2006 at 6:54 am
As you are aware, performing just about any calculation on an indexed column will negate any chance of using the index. Try this... it's simple and makes for nasty fast returns...
DECLARE @FindDate DATETIME
SET @FindDate = '01/01/2001'
SELECT *
FROM yourtable
WHERE somedatecol >= @FindDate
AND somedatecol < @FindDate + 1
--Jeff Moden
Change is inevitable... Change for the better is not.
January 25, 2006 at 7:44 am
I don't think there's a good way to join tables on dates, ignoring times and utilizing an index.
I'd look at alternative solutions if this is something you'll be doing regularly. You could add a date only datetime field to each table and index. Not ideal, but...
January 25, 2006 at 4:51 pm
Dang... didn't read the post close enough... my apologies for the previous lamer post.
--Jeff Moden
Change is inevitable... Change for the better is not.
January 26, 2006 at 2:11 am
Thanks for all the posts.
Luckily I only need to run this query once a month, but having a separate indexed date column seems the best approach.
Thanks all!
January 26, 2006 at 3:47 am
You could use the Convert function to format the date as a string which does not include the time:
e.g.
WHERE Convert(varchar,table1.date,103) = Convert(varchar,table2.date,103)
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply