【问题标题】:TSQL Check if Month and Year fields are expiredTSQL 检查月份和年份字段是否已过期
【发布时间】:2017-11-29 17:06:37
【问题描述】:

我有一个表格,其中月份和年份字段为整数,例如:

Month | Year 
------------
  10  |  17
------------
  11  |  17
------------
  12  |  17
------------
   1  |  18
------------

(第 17 年代表 2017 年,第 18 年代表 2018 年)

我想在查询中添加一个计算字段以检查日期是否过期

SELECT [Year], [Month],
    CASE WHEN 
        ([Year]+2000) < DATEPART(Year, GetDate()) OR 
        (([Year]+2000) = DATEPART(Year, GetDate()) AND [Month] < DATEPART(Month, GetDate())) 
   THEN 1 ELSE 0 END AS IsExpired
FROM test

输出是

Month | Year | IsExpired
------------------------
  10  |  17  |    1
------------------------
  11  |  17  |    1
------------------------
  12  |  17  |    1
------------------------
   1  |  18  |    1
------------------------

预期的输出是(因为当前的 GetDate() 是 2017-11-29):

Month | Year | IsExpired
------------------------
  10  |  17  |    1
------------------------
  11  |  17  |    0
------------------------
  12  |  17  |    0
------------------------
   1  |  18  |    0
------------------------

http://sqlfiddle.com/#!6/8c807/2上观看直播

我做错了什么?

【问题讨论】:

  • 仔细看看你的 sql fiddle。 select * from test 然后仔细查看 Year 和 Month 中的值....它们是倒数的。但老实说,您真正做错的是将部分日期存储在单独的列中。而是使用具有日期数据类型的单个列,您不必跳过箍来进行日期评估。如果您将正确的值放在正确的列中,您的代码就可以正常工作。
  • @SeanLange 哦,谢谢,我很愚蠢...:D

标签: sql sql-server tsql


【解决方案1】:

将您的值转换为日期:

WITH IntDates AS (
    SELECT *
    FROM (VALUES (10,17),(11,17),(12,17),(1,18)) AS D ([Month], [Year])),
Dates AS(
    SELECT *,
       DATEADD(YEAR, [Year], DATEADD(MONTH, [Month], '20000101')) AS DateValue
    FROM IntDates)
SELECT *,
       CASE WHEN DateValue < GETDATE() THEN 1 ELSE 0 END AS Expired
FROM Dates;

【讨论】:

    【解决方案2】:

    如果您使用的是日期数据类型,这会变得简单得多。

    create table test2
    (
        ExpirationDate date
    )
    
    --have to do a bunch of string manipulation to turn this into viable dates.
    --and this of course is after switching the columns posted in your sql fiddle.
    insert test2
    select convert(char(4), [Year] + 2000) + right('0' + convert(varchar(2), [Month]), 2) + '01'
    from Test
    
    select case when ExpirationDate < dateadd(month, datediff(month, 0, getdate()), 0) --get beginning of the current month
            then 1 else 0 end
        , ExpirationDate
    from test2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多