如何将两位数月份变量与单个数字月份变量进行比较?

时间:2017-03-24 02:03:39

标签: sql-server-2008 casting datepart

这就是我所拥有的:

select case when cast(datepart(mm, enrollments.enddate) as varchar)<cast(datepart(mm, getdate()) as varchar)
            then 'Expired'
            when cast(datepart(m, enrollments.enddate) as varchar)=cast(datepart(m, getdate()) as varchar)
            then 'Renewal required by end of this month'
            when cast(datepart(m, enrollments.enddate) as varchar)-1=cast(datepart(m, getdate()) as varchar)
            then 'Renewal required by end of next month'
            when cast(datepart(m, enrollments.enddate) as varchar)>cast(datepart(m, getdate()) as varchar)
            then 'Current'
            Else null
         End) as [Certification Status]

所有逻辑工作除了第一个逻辑之外,其中当enrollments.enddate的月份为12与getdate月份3进行比较时,结果显示12 <3导致输出'Expired'而不是12&gt; 3'当前的“

使用SQL Server 2008

Results - Records incorrectly marked Expired

1 个答案:

答案 0 :(得分:1)

为什么要将比较作为字符串而不是数字进行比较?如果您需要字符串,为什么要使用datepart()代替datename()

所以:

select (case when datepart(month, enrollments.enddat) < datepart(month, getdate())
             then 'Expired'
             when datepart(month, enrollments.enddate) = datepart(month, getdate())
             then 'Renewal required by end of this month'
             when datepart(month, enrollments.enddate) - 1 = datepart(month, getdate())
             then 'Renewal required by end of next month'
             when datepart(month, enrollments.enddate) as > datepart(month, getdate()
             then 'Current'
        End) as [Certification Status]

注意:

  • 使用month代替mmm代替datepart()month对您和其他可能正在阅读代码的人都是明确无误的。
  • 如果您需要字符串,请使用datename(),如果需要数字,请使用datepart()