【问题标题】:Conversion failed when converting date and/or time from character string even though result is correct即使结果正确,从字符串转换日期和/或时间时转换失败
【发布时间】:2026-01-15 23:30:01
【问题描述】:

这是我的查询:

set dateformat mdy;
    select cast([File Date] as date) as 'test' from gpdetail

产生此错误:

消息 241,第 16 级,状态 1,第 2 行 从字符串转换日期和/或时间时转换失败。

知道如何摆脱错误吗?任何非常感谢的帮助已经停留了很长时间:(

但是,在结果选项卡下,它会显示正确的结果

这是实际数据

【问题讨论】:

  • 您可能在某处有一条格式不正确的记录,因此它无法转换整个内容。如果你有 SQL 2012,你试试TRY_CONVERT 并检查结果以查看哪一行返回 null,这将是你的“坏”记录
  • 以下是否对您有更好的效果:convert(datetime, [File Date], 1)
  • 表格有多少行?只是你给我们看的6个?可能它在下一行失败了。向我们展示其中包含的内容。
  • 消除错误的最佳方法是发送至store your data with the appropriate data type。您发布的问题的任何答案我都会考虑解决,而不是解决方案。在纠正数据未正确存储的根本问题之前,您将继续遇到问题。

标签: sql sql-server tsql


【解决方案1】:

isdate()函数开始:

select [File Date]
from gpdetail
where isdate([File Date]) = 0;

这可能会找到日期不符合的地方。

如果您只想忽略格式错误的字符串,请尝试:

select (case when isdate([File Date]) = 1 
             then cast([File Date] as date) 
        end) as test
from gpdetail

【讨论】:

  • @感谢先生的解释,它也对我有用。 :)
  • 我遇到的一个微妙的烦恼是避免使用 ELSE 子句,否则将无条件评估 THEN 导致错误 241...