SQL Server:检查所选日期是否比当前日期更旧或更新

时间:2014-04-27 12:31:49

标签: sql sql-server date datetime stored-procedures

我使用以下存储过程选择数据,dateDT保存为datetime。

有没有办法可以使用CASE检查每个选定的日期,无论是旧的还是比当前日期更新,并添加一个简短的文字(例如'过去'或者' future& #39;)为此选择?

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')

非常感谢,迈克。

2 个答案:

答案 0 :(得分:3)

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')

答案 1 :(得分:1)

假设该字段是日期:

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')

如果只是想要查看日期组件,而不是时间,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

请注意,在这些示例中,没有任何函数应用于dateDT列。这是一个很好的习惯,虽然它对case语句没有影响。但是,当在where子句中使用时,它可以在性能上产生很大的不同。