Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Fastest way to compare two dates (non standard varchar format and datetime)

I have two "date" fields that I need to join on.

The first is a normal datetime in the format yyyy-mm-dd hh:mm:ss

The second is a varchar(8) in the red-headed step child format mmddyyyy

Now this gets painful because there is no easy way to convert to the corresponding type. There is a built-in format that is yyyymmdd but that doesn't match the varchar format.

There are two paths I can see:

declare @normal_date as datetime;
declare @hated_date as varchar(8);

set @normal_date='1974-11-01 00:00:00.000'
set @hated_date='11011974'

--cast to date time with string splits
select @normal_date
where CONVERT(datetime, RIGHT(@hated_date,4)+LEFT(@hated_date,2)+SUBSTRING(@hated_date,3,2))=@normal_date

--convert normal date to ackward format
select @normal_date
      where REPLACE(CONVERT(varchar(10),@normal_date,101), '/','')=@hated_date

Which is better? Or is there a better way?

Edited to show costs

--Operator cost (39%)
CONVERT(datetime, RIGHT(@hated_date,4)+LEFT(@hated_date,2)+SUBSTRING(@hated_date,3,2))=@normal_date

--Operator cost (57%)
REPLACE(CONVERT(varchar(10),@normal_date,101), '/','')=@hated_date

--Operator cost (46%)
cast(stuff(stuff(@hated_date, 3,0, '/'),6,0,'/') as datetime)=@normal_date

--Operator cost (47%)
RIGHT(@hated_date, 4) + LEFT(@hated_date, 4)=@normal_date
like image 786
Nix Avatar asked Dec 22 '22 23:12

Nix


1 Answers

This is yyyymmdd no?

RIGHT(@hated_date, 4) + LEFT(@hated_date, 4)

So, your script becomes

declare @normal_date as datetime;
declare @hated_date as varchar(8);

set @normal_date='1974-11-01 00:00:00.000'
set @hated_date='11011974'

--SELECT @hated_date = RIGHT(@hated_date, 4) + LEFT(@hated_date, 4))

select 'hurrah' WHERE @normal_date = RIGHT(@hated_date, 4) + LEFT(@hated_date, 4)
like image 197
gbn Avatar answered Mar 08 '23 23:03

gbn