【问题标题】:check date between two dates or NULL in sql检查两个日期之间的日期或sql中的NULL
【发布时间】:2013-09-16 15:57:13
【问题描述】:

我想在between two dates 中传递check date 或者可以传递为NULL 使用存储过程

代码

declare @fromDate date = null
declare @toDate date = null

select * from Mytable 
where date betweeen @fromDate and @toDate OR NULL (how to check for both parameters)

我还有另外 2 个参数,所以应该显示与日期无关的结果。 如果@todate 和@fromDate 为NULL

请帮忙。

【问题讨论】:

  • 如果@toDate 为空,你需要什么结果?
  • 我还有另外 2 个参数,所以应该显示与日期结果无关的参数

标签: mysql sql sql-server tsql


【解决方案1】:

试试下面的合并功能

declare @fromDate date = null
declare @toDate date = null

select * from Mytable 
where date between coalesce(@fromDate,date) and coalesce(@toDate,date)

【讨论】:

  • @parado 测试这对于等于@fromDate@toDate 的日期仅严格 不起作用。 - 所以@fromDate 必须是 - 1 天或 toDate + 1 天。 - 如果我没看错的话。
  • @Pakk 我不知道你的情况,但我检查了上面的解决方案 - 它有效
  • @Parado 我已经找到了原因——我的错。我的日期正在寻找 Date + '00:00:00:0000' 到 Date + '00:00:00:0000'。 - 我错过了时间跨度。感谢您的代码。
【解决方案2】:

几乎可以将您的英语转换为 SQL:

where (date is null or date betweeen @fromDate and @toDate)

【讨论】:

  • 不确定,但我认为 OP 意味着参数可以为 null 而不是日期字段。
  • 那个语法不起作用我使用了 coalesce 而不是 IS NULL :)
【解决方案3】:

在寻找比"between""coalesce" 更好的解决方案时,我发现了这个帖子:

  • 火鸟 SQL
  • param 永远不会为 NULL
  • createdatum 永远不会为 NULL
  • offdatum 可以为 NULL - 原因很明显 ;)

初步解决方案:

where
    X = :X
    AND
    cast(:QryDateTime as DATE) between
      createdatum and coalesce(offdatum, cast(:QryDateTime as DATE))

问题有点棘手:当使用“现在”作为 QryDateTime 的值时,(很少)没有找到结果 - 即使应该存在一个

问题是 now 每次都单独评估,显然不是按照从左到右的顺序。

我终于改成了:

where
    X = :X
    AND
    iif(offdatum is null, 1, iif(offdatum > cast(:QryDateTime as DATE), 1, 0)) = 1
    AND
    cast(:QryDateTime as DATE) > createdatum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2019-08-05
    • 2018-07-25
    相关资源
    最近更新 更多