我有两个“日期”字段,我需要加入的。比较两个日期(非标准格式的varchar和日期)SQL最快的方式
首先是格式yyyy-mm-dd hh:mm:ss
第二正常日期时间为varchar(8)在红头继子女格式mmddyyyy
现在,因为没有简单的方法来此得到痛苦转换为相应的类型。有一种内置格式,即yyyymmdd
,但与varchar格式不匹配。
有两条路我可以看到:
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))[email protected]_date
--convert normal date to ackward format
select @normal_date
where REPLACE(CONVERT(varchar(10),@normal_date,101), '/','')[email protected]_date
哪个更好?或者,还有更好的方法?
编辑,以显示成本
--Operator cost (39%)
CONVERT(datetime, RIGHT(@hated_date,4)+LEFT(@hated_date,2)+SUBSTRING(@hated_date,3,2))[email protected]_date
--Operator cost (57%)
REPLACE(CONVERT(varchar(10),@normal_date,101), '/','')[email protected]_date
--Operator cost (46%)
cast(stuff(stuff(@hated_date, 3,0, '/'),6,0,'/') as datetime)[email protected]_date
--Operator cost (47%)
RIGHT(@hated_date, 4) + LEFT(@hated_date, 4)[email protected]_date
来自执行计划的运营商成本毫无意义。您需要使用'SET STATISTICS IO ON'运行每一百万次并进行比较。我想你会发现其中大部分都差不多。 – ErikE 2010-09-24 00:38:23