我有兩個「日期」字段,我需要加入的。比較兩個日期(非標準格式的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