与 'convert' 函数一起使用时 Where 子句失败

Where clause fails when used with a 'convert' function

我正在将表示日期的 varchar 字段转换为日期时间,并在 "where - between" 子句中使用它。

我得到:

Conversion failed when converting date and/or time from character string

我的 where 子句是:

select
screen_date
from d8003
where convert(datetime, screen_date, 120) between '6/1/2018' and '12/31/2018'

我该如何解决这个问题?

尝试使用以下语法(使用 YYYYMMDD 日期格式而不是 MM/DD/YYYY):

select
screen_date
from d8003
where convert(datetime, screen_date, 120) between '20180601' and '20181231'

如果您仍然遇到同样的错误,请检查您是否使用了正确的日期格式代码:

2005 年之前的错误处理能力非常有限。 对于 SQL 2005+ 这应该有效

declare 
     @date_value varchar(50)
    ,@tmp datetime;
declare x cursor local fast_forward 
for
select screen_date from d8003

open x;
fetch next from x into @date_value;
while @@fetch_status = 0
    begin
        begin try
            set @tmp = convert(datetime,@date_value, 120)
        end try
        begin catch
            select 'This one is bad! Please fix me!! (' + rtrim(@date_value) + ')' bad_values;
        end catch
        fetch next from x into @date_value;
    end
close x;
deallocate x;
GO

这将 return 您 SQL 2012 年以后的不良数据 try_convert,将 return 不可转换字符串上的 null。

select 
    try_convert(datetime, screen_date, 120) mytryconvert
    ,screen_date
from d8003
where try_convert(datetime, screen_date, 120) is null

您可以手动更正数据或使用字符串操作内联。

如果您不确定该值是否真的可以转换,请使用 TRY_CAST

但请注意,您收到此错误可能表明您的列中的某些记录存在问题。如果您只关心获取 varchar 列实际上可以转换为日期时间的记录,请仅使用 TRY_CAST。

SELECT
    [screen_date]
FROM
    [d8003]
WHERE
    TRY_CAST([screen_date] AS DATETIME) BETWEEN '6/1/2018' AND '12/31/2018'

感谢您提供的所有建议和帮助。我很高兴地告诉您我找到了解决方案。这是我的代码:

其中 try_cast(screen_date 作为小日期时间)在“2018-06-01”和“2018-12-31”之间

这是一位有多年经验的同事的建议。 (我刚开始编码 SQL ....)

这是你们中的一个人之前的建议,我不确定为什么当时没有用。

德古萨