将表达式转换为数据类型datetime的算术溢出错误.(显示日期时间..)

Nis*_*sar 9 sql-server stored-procedures

执行以下错误时显示

declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;
select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT
Run Code Online (Sandbox Code Playgroud)

错误显示

Arithmetic overflow error converting expression to data type datetime.
Run Code Online (Sandbox Code Playgroud)

Ian*_*ton 14

你问的是你正在尝试convert将数字转换为a datetime,而这只是不起作用.

你需要numeric先把你变成一个字符串:

declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;

select yr_mnth_dt = cast(cast(@yr_mnth_dt as char(8)) as datetime);
Run Code Online (Sandbox Code Playgroud)

SQL小提琴演示.

当您尝试将数字类型转换为a时datetime,SQL Server会尝试将数值添加为日期的天数01-Jan-1900.在你的情况下,这是试图增加数百万天,因此溢出错误.

CONVERT 如果您愿意,也可以正常工作:

select yr_mnth_dt = convert(datetime, convert(char(8), @yr_mnth_dt));
Run Code Online (Sandbox Code Playgroud)

SQL小提琴演示.