这种try_convert用法有什么问题?



我试图使用mssql2012中的新try_convert功能将日期/时间/偏移量字符串转换为datetimeoffset。

字符串看起来像:2013-04-25T21:56:58.077-05:00

这是代码——我知道这个解析不会工作,所以我期待结果击中"IS NULL"并返回"Cast Failed"。事实并非如此——相反,我仍然得到Msg 241日期转换错误。什么好主意吗?

case  
   when try_convert(datetimeoffset, (cast(substring(lift.PlannedLiftDateTime,1,10) + ' ' + substring(lift.PlannedLiftDateTime,12,8) + ' ' + substring(lift.PlannedLiftDateTime,20,6) as datetimeoffset))) IS NULL
    then 'Cast Failed'
   when ltrim(rtrim(lift.PlannedLiftDateTime)) = ''
    then NULL
   else
    '~' + lift.PlannedLiftDateTime + '~'
end as PlannedLiftDateTime,

由于CAST语句try_convert - try_convert不会消耗您生成的所有错误,如果转换失败,它只会返回NULL

如果您使用try_convert两次尝试,它将工作:

when try_convert(datetimeoffset, (try_convert(datetimeoffset, substring(@DateString,1,10) + ' ' + substring(@DateString,12,8) + ' ' + substring(@DateString,20,6)))) IS NULL

最新更新