使用 getdate()

Using getdate()

我正在使用以下查询

SELECT *
    FROM [dbo].[QUANTITY] 
    WHERE getdate() BETWEEN fromdate AND todate

如果 todatenull (1900-01-01 00:00:00.000),它只是将它们过滤掉。我什至希望结果中带有 todate 的字段为 null (1900-01-01 00:00:00.000)。如何做到这一点?

您可以使用 andor 运算符的组合明确检查它:

SELECT *
FROM   [dbo].[QUANTITY] 
WHERE  (getdate() >= fromdate AND
        (todate IS NULL OR
         todate = '1900-01-01 00:00:00.000')
       ) OR
       getdate() BETWEEN fromdate AND todate

似乎在线的某个地方有一个 .Net 或一些程序保存了 Date.MinValue,如果应用程序无法被替换,你总是可以添加一个

datefromparts(1900,1,1)

并将 where 子句更改为:

where getdate() > fromdate
and (todate = datefromparts(1900,1,1) or getdate() <= todate)

这将采用今天的最大值或无限值。如果可能的话,为了防止出现奇怪的结果,我也会使用

declare @testDate datetime = getdate(); 

并在前面的 where 子句中使用该变量而不是 getdate()。

SELECT *
FROM [dbo].[QUANTITY] 
WHERE getdate() >= fromdate
  AND getdate() <= COALESCE(todate
                           ,NULLIF(todate,'1900-01-01 00:00:00.000')
                           ,'9999-12-31 23:59:59.997'
                           )