SQL 两年之间的日期相减
我尝试从 MS Access 转换查询时遇到问题。当查询标记记录超过 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)
当我在 MS Access 中运行此查询时,我总共获得了 3793 条标记记录,但在 SQL Server 中,我获得了 69061 条标记为删除的记录。 GetDate()-90 值在 10/26/2010 时是正确的,但它标记了今年以来的所有内容都将被删除。
我确信这是我所忽略的简单事情。请帮忙?
我想通了:
UPDATE DT.SM_T_CountTotals
SET IsActive = 0
WHERE DT.SM_T_CountTotals.PostDate < Convert(varchar, GetDate()- 90, 101)
I am having an issue with a query I am trying to convert from 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.
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. The GetDate()-90 value is correct at 10/26/2010 but it is flagging everything from this year to be removed.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在比较 VARCHAR 值,而不是 DATE。
101 转换为 MM/DD/YY,因此您要比较月份,然后比较日期,然后比较年份。
您应该使用 112 (yymmdd)
You're comparing VARCHAR values, not DATEs.
101 converts to MM/DD/YY, so you're comparing month, then day, then year.
You should be using 112 (yymmdd)
两个日期之间的计算可以在本机数据类型中轻松完成,而不是将其转换为字符串。人们可以(并且你已经)从这样的转换中得到不正确的答案。
在 where 子句中使用
DateDiff
来获取超过 90 天的记录。http://msdn.microsoft.com/en-us/library/ms189794.aspx
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.http://msdn.microsoft.com/en-us/library/ms189794.aspx