SQL Server:从字符串转换时间时转换失败

时间:2018-12-31 22:11:45

标签: sql sql-server datetime

我下面有一列,其数据类型为char(24),但数据中包含日期

我想将数据转换为datetime,以便可以像这样从过去的一个小时中选择数据:

Where CounterDateTime   >= DateAdd(hour, -1, getDate())

但是我不断收到错误消息:

  

从字符串转换日期和/或时间时转换失败

即使我将我的CounterDateTime转换为datetime也是如此。请帮忙。

2 个答案:

答案 0 :(得分:0)

您可以像这样将列强制转换为日期时间:

Where CounterDateTime IS NOT NULL AND Cast(RTRIM(LTRIM(CounterDateTime)) as DateTime) >= DateAdd(hour, -1, getDate())

这也可能起作用:

Where CounterDateTime IS NOT NULL AND CONVERT(datetime, RTRIM(LTRIM(CounterDateTime)), 121) >= DateAdd(hour, -1, getDate())

还有1个:

Where CounterDateTime IS NOT NULL AND try_parse(RTRIM(LTRIM(CounterDateTime)) as DateTime using 'en-US') >= DateAdd(hour, -1, getDate())

答案 1 :(得分:0)

不将日期/时间值存储为字符串。这可能会导致问题。

下一个大问题是依赖隐式转换。如果必须转换值,请明确进行转换。所以:

Where try_convert(datetime, CounterDateTime) >= DateAdd(hour, -1, getDate())

您显然拥有无法转换的值。你不知道为什么。您可以使用查询找到这些值:

select CounterDateTime
from t
where try_convert(datetime, CounterDateTime) is null and
      CounterDateTime is not null;

这将返回无法转换的非NULL值。

相关问题