我正在将表示日期的varchar字段转换为datetime,并在qazxsw poi子句中使用它。
我明白了:
从字符串转换日期和/或时间时转换失败
我的"where - between"
条款是:
where
我该如何解决这个问题?
尝试使用以下语法(使用YYYYMMDD日期格式而不是MM / DD / YYYY):
select
screen_date
from d8003
where convert(datetime, screen_date, 120) between '6/1/2018' and '12/31/2018'
如果仍然出现相同的错误,请检查您是否使用了正确的日期格式代码:
select
screen_date
from d8003
where convert(datetime, screen_date, 120) between '20180601' and '20181231'
2005年之前,错误处理能力非常有限。对于SQL 2005+,这应该工作
Date and Time Conversions Using SQL Server
这将在SQL 2012+ try_convert中返回您的错误数据,将在不可转换的字符串上返回null。
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
您可以手动更正数据或使用字符串操作内联。
如果您不确定该值是否可以实际转换,请使用select
try_convert(datetime, screen_date, 120) mytryconvert
,screen_date
from d8003
where try_convert(datetime, screen_date, 120) is null
。
但请注意,您收到此错误的事实可能表明您的专栏中的某些记录存在问题。如果您只关心获取varchar列实际上可以转换为日期时间的记录,请仅使用TRY_CAST。
TRY_CAST
感谢您提供的所有建议和帮助。我很高兴地告诉你,我找到了解决方案。这是我的代码:
'2018-06-01'和'2018-12-31'之间的try_cast(screen_date为smalldatetime)
这是一位拥有多年经验的同事的建议。 (我刚开始用SQL编写代码....)
这是你们之前的一个建议,我不知道为什么它不起作用。
Deguza