将整数转换为日期并根据此日期获取记录

converting integer to date and getting records based on this date

我有一个 table (SQLServer 2008r2),它有一个整数,它是一个日期。格式是 YYYYMMDD(不,我对此没有设计控制权,也不会选择这样做。它无法更改)。

我想将其转换为日期并获取该字段值小于当前日期减去 14 天的所有记录。这就是我正在使用的:

SELECT * from webFormsInstances where formStage <> 'Complete' 
AND cast(convert(DATETIME, LEFT(formActionDate, 8)) as date) < dateAdd(day,-14,getdate())
order by formActionDateTime desc

有没有更好更高效的方法来做到这一点?

如果在列上使用公式,sqlserver 将无法在列上使用任何索引,因为它必须对所有行执行计算。 (寻找 sargable。例如 here

改为对常量进行计算。

SELECT *
FROM webFormsInstances 
WHERE formStage <> 'Complete' 
      AND formActionDate < CONVERT(int, CONVERT(varchar(8), dateAdd(day,-14, getdate()), 112))
ORDER BY formActionDateTime DESC

请检查这个。

declare @t table(id int, formStage varchar(50),  formActionDate int)

insert into @t values (1 ,'notComplete', 20150101), (2 ,'Complete', 20150128),(3 ,'notComplete', 20150129),(2 ,'notComplete', 20150131),(3 ,'notComplete', 20150201),(4 ,'notComplete', 20150209),(5 ,'notComplete' , 20150220), 
(6 ,'notComplete', 20150115),(7,'notComplete', 20150113)

select CONVERT(DATETIME, cast(formActionDate as varchar) ,114),* from @t 
where formStage <> 'complete'

SELECT * from @t where formStage <> 'Complete' 
AND --cast(convert(DATETIME, LEFT(formActionDate, 8)) as date) 
CONVERT(DATETIME, cast(formActionDate as varchar) ,114)
< dateAdd(day,-14,getdate())
order by formActionDate desc