SQL 你如何测试东西是否超过 3 个月?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6931619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:34:35  来源:igfitidea点击:

How do you test if something is older than 3 months?

sqlsql-servertsql

提问by Eon

I have been having some trouble to select the rows of my table which has a date of 3 months prior of today. I tried using DATE(NOW() - INTERVAL 3 MONTH)in my where clause, but no luck. How do I check in SQL Server if a item is older than 3 months?

我在选择日期为今天之前 3 个月的表中的行时遇到了一些麻烦。我尝试DATE(NOW() - INTERVAL 3 MONTH)在我的 where 子句中使用,但没有运气。如果项目超过 3 个月,我如何在 SQL Server 中进行检查?

  UPDATE[TCTdb].[dbo].[Stock]
     SET[Warehouse] = 'old'
   WHERE [ManufacturedDate] <= DATE(NOW() - INTERVAL 3 MONTH)

回答by Code Magician

Your syntax appears to be wrong.

您的语法似乎是错误的。

That should be

那应该是

UPDATE[TCTdb].[dbo].[Stock]
    SET[Warehouse] = 'old'
WHERE [ManufacturedDate] <= DATEADD(mm, -3, GETDATE())

回答by canon

Use dateadd().

使用dateadd().

update [TCTdb].[dbo].[Stock]
set [WareHouse] = 'old'
where [ManufacturedDate] < dateadd(month,-3,getdate())

I suggest dateadd()over datediff()because I think you're going to get unexpected results using datediff()with the monthdatepart.

我建议dateadd()datediff(),因为我觉得你会得到意想不到的使用效果datediff()month日期部分。

Consider that the following statements both return 3:

考虑以下语句都返回3

select datediff(month, '1/1/2011','4/1/2011')
select datediff(month, '1/1/2011','4/30/2011')

Either works in this particular case... Just keep that behavior in mind.

要么在这种特殊情况下工作......请记住这种行为。

回答by hspain

The DATEDIFF function should be helpful to you:

DATEDIFF 函数应该对您有所帮助:

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

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

UPDATE[TCTdb].[dbo].[Stock]
    SET[Warehouse] = 'old'
    WHERE DATEDIFF(month, [ManufacturedDate], GETDATE()) > 3

回答by JohnD

try out DATEDIFF:

试试 DATEDIFF:

SELECT 
    case 
        when DATEDIFF(month, '2005-12-31' , '2006-04-01 ') > 3
        then 'yes'

        else 'no'

    end

Hope that helps,

希望有所帮助,

John

约翰