【问题标题】:Use one of two dates in where clause在 where 子句中使用两个日期之一
【发布时间】:2022-01-20 17:56:56
【问题描述】:

我需要删除表中 CreatedDate 或 ModifiedDate 大于 x 的所有记录。逻辑如下:

  • 如果 ModifiedDate 不为空,则使用此值
  • 否则使用 CreatedDate 值

没有正确应用 if/else 语句。

delete * from table where
-- how to implement the following
if ModifiedDate is not null then ModifiedDate < GETDATE() - 30
else CreatedDate < GETDATE() - 30

【问题讨论】:

  • 欢迎来到 Stack Overflow!日期函数在不同品牌和版本的 SQL 表服务器中的工作方式不同。请edit您的标签告诉我们您使用的是哪一个。
  • 请阅读 - docs.microsoft.com/en-us/sql/t-sql/language-elements/…。它会帮助你正确表达。
  • 您说大于但您的示例代码检查小于?

标签: sql date where-clause


【解决方案1】:

使用这个 where 子句:

where coalesce(ModifiedDate, CreateDate) < dateadd(day, -30, getdate())

【讨论】:

  • 谢谢!效果很好。
  • 如果有帮助,您可以接受答案。
【解决方案2】:

用例说明

Delete * From tableX
CASE WEHN  ModifiedDate is not null and < Getdate() - 30 THEN -- your logic
Else -- CreateDate < Getdate() - 30 END

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2013-07-17
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多