简体   繁体   English

SQL Server:检查所选日期是否早于或晚于当前日期

[英]SQL Server: check if selected date is older or newer than current date

I am selecting data using the following stored procedure with dateDT being saved as datetime. 我正在使用以下存储过程选择数据,其中dateDT被保存为datetime。

Is there a way I can use CASE to check for each of the selected dates whether it is older or newer than the current date and add a short text (eg 'past' or 'future') for this to the Select ? 有没有一种方法可以使用CASE来检查每个选定日期是否早于或晚于当前日期,并为此向Select添加一个短文本(例如“ past”或“ future”)?

SELECT      dateID,
            CONVERT(VARCHAR(11), dateDT, 106) AS dateDT,
            CONVERT(VARCHAR(10), dateDT, 126) AS dateDTShort,
            countries,
            regions
FROM        DaysFixed
WHERE       countries LIKE '%'+@selCountry+'%'
OR          regions LIKE '%'+@selCountry+'%'
ORDER BY    dateID
FOR XML PATH('datesDT'), ELEMENTS, TYPE, ROOT('root')

Many thanks in advance, Mike. 谢谢你,迈克。

SELECT      dateID,
            CONVERT(VARCHAR(11), dateDT, 106) AS dateDT,
            CASE WHEN CONVERT(VARCHAR(11), dateDT, 106) > GETDATE() THEN 'Future' 
            ELSE 'Past' END AS FutureOrPast,
            CONVERT(VARCHAR(10), dateDT, 126) AS dateDTShort,
            countries,
            regions
FROM        DaysFixed
WHERE       countries LIKE '%'+@selCountry+'%'
OR          regions LIKE '%'+@selCountry+'%'
ORDER BY    dateID
FOR XML PATH('datesDT'), ELEMENTS, TYPE, ROOT('root')

Assuming that the field is a date: 假设该字段是一个日期:

SELECT      dateID,
            CONVERT(VARCHAR(11), dateDT, 106) AS dateDT,
            CONVERT(VARCHAR(10), dateDT, 126) AS dateDTShort,
            (CASE WHEN dateDT < GETDATE() then 'PAST' else 'FUTURE' end) as TimeWhen,
            countries,
            regions
FROM        DaysFixed
WHERE       countries LIKE '%'+@selCountry+'%'
OR          regions LIKE '%'+@selCountry+'%'
ORDER BY    dateID
FOR XML PATH('datesDT'), ELEMENTS, TYPE, ROOT('root')

If you just want to look at the date component, and not the time, and dateDT is a date and not a datetime : 如果您只想查看日期组件,而不是时间,并且dateDTdate而不是datetime

            (CASE WHEN dateDT < cast(GETDATE() as date) THEN 'PAST'
                  WHEN dateDT = cast(GETDATE() as date) then 'PRESENT'
                  WHEN dateDT > cast(GETDATE() as date) THEN 'FUTURE'
             END) as TimeWhen

Note in these examples that no functions are applied to the dateDT column. 请注意,在这些示例中,没有函数应用于dateDT列。 This is a good habit to get into, although it does not make a difference for a case statement. 这是一个很好的习惯,尽管对case陈述没有影响。 When used in a where clause, however, it can make a big difference in performance. 但是,当在where子句中使用时,它可以在性能上产生很大的不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM