简体   繁体   English

两年之间的SQL日期减法

[英]SQL Date Subtraction Between Two Years

I am having an issue with a query I am trying to convert from MS Access. 我正在尝试从MS Access转换的查询有问题。 The query flags record for removal when it is older than 90 days but when I convert this query to sql server is is removing too many records. 查询标记记录,以便在超过90天时删除,但是当我将此查询转换为sql server时,会删除太多记录。

UPDATE  DT.SM_T_CountTotals
       SET  IsActive = 0
WHERE Convert(varchar, DT.SM_T_CountTotals.PostDate, 101) <
        Convert(varchar, GetDate()- 90, 101) 

When I run this query in MS Access I get a total of 3793 records that are flagged but in SQL server I get 69061 records that are flagged for removal. 当我在MS Access中运行此查询时,我总共获得了3793条被标记的记录,但在SQL服务器中,我获得了69061条被标记为要删除的记录。 The GetDate()-90 value is correct at 10/26/2010 but it is flagging everything from this year to be removed. GetDate() - 90值在2010年10月26日是正确的,但它正在标记今年要删除的所有内容。

I am sure it is something easy that I am overlooking. 我确信这是我容易忽视的事情。 Help please? 请帮助?

I figured it out: 我想到了:

UPDATE  DT.SM_T_CountTotals
   SET  IsActive = 0
WHERE DT.SM_T_CountTotals.PostDate < Convert(varchar, GetDate()- 90, 101) 

You're comparing VARCHAR values, not DATEs. 您正在比较VARCHAR值,而不是DATE。

101 converts to MM/DD/YY, so you're comparing month, then day, then year. 101转换为MM / DD / YY,因此您要比较月,日,然后年。

You should be using 112 (yymmdd) 你应该使用112(yymmdd)

Calculations between two dates can be easily done in the native data type rather than convert it to string. 两个日期之间的计算可以在本机数据类型中轻松完成,而不是将其转换为字符串。 One can (and you have) get incorrect answers from such conversions. 人们可以(并且你有)从这种转换中得到错误的答案。

Use DateDiff in the where clause to get the records that are more than 90 days old. 在where子句中使用DateDiff来获取超过90天的记录。

http://msdn.microsoft.com/en-us/library/ms189794.aspx http://msdn.microsoft.com/en-us/library/ms189794.aspx

UPDATE  DT.SM_T_CountTotals
SET  IsActive = 0
WHERE ABS (DATEDIFF (dd, Getdate(), DT.SM_T_CountTotals.PostDate)) > 90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM