从字符串转换日期 and/or 时间时转换失败。过滤 sql select 查询时

Conversion failed when converting date and/or time from character string. when filtering sql select query

我有一个相对基本的查询,关于哪些日期保存在 table 中作为 nvarchar(200)。

我正在尝试对如下所示的 InteractionDate 字段进行筛选

'02-03-2018 12:00', '03-04-2018 14:46', '03-04-2018 14:44' etc.

但是在尝试转换 nvarchar 日期字段时出现错误 Conversion failed when converting date and/or time from character string.

这就是查询的样子

 select
 act.InteractionDate,
 act.Status
 from JobCanvas_B2B canvas
  inner join PersonActivity_JobCanvas inters on inters.CanvasId = 
  canvas.CanvasId
   inner join PersonActivity act on act.PersonActivityId = 
    inters.PersonActivityId 
    inner join Stage s on s.StageId = act.StageId
     where convert(date, act.InteractionDate, 101) > convert(date, '01-01-2018 12:00', 101)

我怎样才能正确地进行这个日期转换以便查询有效?

这成功了,

  where convert(date, act.InteractionDate, 103) > convert(date, '01-01-2018 12:00', 103)

如果您可以容忍只处理日期部分,请像您在回答中那样使用掩码 103。如果您还需要时间组件,那么我们可以尝试通过格式掩码 120,同时进行一些字符串操作:

CONVERT(datetime, SUBSTRING(act.InteractionDate, 7, 4) + '-' +
     SUBSTRING(act.InteractionDate, 4, 2) + '-' + LEFT(act.InteractionDate, 2) +
     ' '  + RIGHT(act.InteractionDate, 5), 120)

Demo

理想情况下,我们应该能够直接使用掩码 131,但我无法让它工作,至少不能使用您拥有的数据类型。相反,上面的代码片段手动构建了 yyyy-mm-dd hh:mi:ss.

格式的时间戳

最好的长期解决方案是不要将日期信息存储为文本。如果您必须这样做,那么您的 ISO 格式很容易用 SQL 服务器的内置函数转换。