TSQL Vérifie si les champs Mois et Année ont expiré

J'ai une table avec les champs Mois et Année comme entier, par exemple:

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

(L'année 17 est pour 2017 et l'année 18 est pour 2018)

Je veux append dans une requête un champ calculé pour vérifier si la date est expirée

 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 

la sortie est

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

la sortie attendue est (car GetDate () actuel est 2017-11-29):

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

voir en direct sur http://sqlfiddle.com/#!6/8c807/2

ce que je fais mal?

Convertissez vos valeurs en dates:

 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; 

Si vous utilisiez le datatype, cela devient beaucoup plus simple.

 create table test2 ( ExpirationDate date ) --have to do a bunch of ssortingng manipulation to turn this into viable dates. --and this of course is after switching the columns postd 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