【问题标题】:Arithmetic overflow error converting expression to data type datetime. (while displaying date time..)将表达式转换为数据类型日期时间的算术溢出错误。 (在显示日期时间时..)
【发布时间】:2013-08-24 08:40:26
【问题描述】:

执行时显示以下错误

declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;
select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT

错误显示

Arithmetic overflow error converting expression to data type datetime.

【问题讨论】:

  • 我通常看到像处理字符串而不是数字的转换表达式。一定要从数字类型开始吗?

标签: sql-server stored-procedures


【解决方案1】:

您的问题是您尝试将convert 数字转换为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);

SQL Fiddle with demo.

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

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

select yr_mnth_dt = convert(datetime, convert(char(8), @yr_mnth_dt));

SQL Fiddle with demo.

【讨论】:

    【解决方案2】:

    我只看到了用于字符串的转换。我无法轻易判断它是否设计用于处理数字。您可以将数字转换为字符串,然后将字符串转换为日期。但是,我个人只会使用DATEFROMPARTS

    SELECT DATEFROMPARTS(@yr_mnth_dt / 10000, 
                         (@yr_mnth_dt / 100) % 100,
                         @yr_mnth_dt % 100) AS YR_MNTH_DT
    

    【讨论】:

    • 这是一个很好的方法,但值得注意的是它仅适用于 SQL Server 2012 及更高版本。
    • @IanPreston:没有注意到这一点。 当然有一些方法可以在不使用字符串的情况下从其组成部分创建日期...
    【解决方案3】:

    为什么是数字? 试试这个

    declare @yr_mnth_dt as varchar(10);
    set @yr_mnth_dt = '20130822';
    select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT
    

    【讨论】:

    • 根据 OP 的 cmets,他必须以 numeric 类型开头。
    • @Ian Preston,但我看到它是 2013 年 8 月 22 日,而不是整数。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多