【问题标题】:SQL Find/Ignore invalid dateSQL 查找/忽略无效日期
【发布时间】:2017-06-20 12:13:50
【问题描述】:

我正在使用 SQL Server。

从每一行中,我从字段 c.daybirth,c.monthbirth 中获取日期和月份值 以及 getdate() 的年份,我想要一个字段来显示此日期是否有效(无效示例:2 月 31 日)

我已经创建了这个解决方案:

case day(dateadd(month,c.monthbirth-1,dateadd(day,c.daybirth-1,DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)))) when c.daybirth then 1 else 0 end

这行得通,但我觉得很难阅读。有更聪明的选择吗?

【问题讨论】:

    标签: sql sql-server tsql date


    【解决方案1】:

    在 SQL Server 2012+ 中,您可以:

    where try_convert(date,
                      datefromparts(year(getdate()), c.monthbirth, c.daybirth)
                     ) is not null
    

    编辑:

    有趣。这样更好:

    where try_convert(date,
                      cast(year(getdate()) * 10000 + c.monthbirth * 100 + c.daybirth as varchar(255))
                     ) is not null
    

    【讨论】:

    • 这不会运行,因为 datefromparts 已经抛出错误。但是,如果我用适当的字符串替换 datefromparts,我可以得到你想要的。谢谢。
    • 代码:try_convert(date,convert(nvarchar,c.daybirth)+'-'+convert(nvarchar,c.monthbirth)+'-'+convert(nvarchar,year(getdate()) ),103)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多