这个try_convert用法有什么问题?

pld*_*llo 3 sql t-sql sql-server case-when sql-server-2012

我试图在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,
Run Code Online (Sandbox Code Playgroud)

JNK*_*JNK 5

你得到,因为的错误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

在这里编写代码的小提琴.