【问题标题】:How can I compare a two digit month variable with a single digit month variable?如何将两位数月份变量与一位数月份变量进行比较?
【发布时间】:2017-03-24 02:03:39
【问题描述】:

这是我所拥有的:

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]

除了第一个逻辑之外,所有逻辑都有效,其中当将 12 月的enrollments.enddate 与 getdate 月 3 进行比较时,结果显示 123 '当前'

使用 SQL Server 2008

【问题讨论】:

  • 停止转换为 VARCHAR,改用数值。

标签: sql-server-2008 casting datepart


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多