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

时间:2015-02-09 06:22:07

标签: sql tsql sql-server-2008-r2

我有一个表(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

有更好的方法来这样做吗?

2 个答案:

答案 0 :(得分:1)

如果在列上使用公式,则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

答案 1 :(得分:0)

请检查一下。

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