【问题标题】:he conversion of a char data type to a datetime data type resulted in an out-of-range datetime value将 char 数据类型转换为 datetime 数据类型导致超出范围的 datetime 值
【发布时间】:2019-12-23 19:27:20
【问题描述】:

我正在执行以下查询,但出现以下错误。

INSERT INTO [dbo].[Calendar]  ([ID],[Year],[Quarter],[Week],[Stdate],[EdDate])
VALUES (680, 2020, 1, 1, convert(datetime,'30-06-2019 00:00:00 AM'), convert(datetime,'06-07-2019 23:59:00 PM'));

错误信息:

char 数据类型到 DateTime 数据类型的转换导致 超出范围的 DateTime 值。

【问题讨论】:

  • 请注意:SQL Server 2005 已经不再提供扩展支持已有一段时间了;升级时间紧迫!

标签: sql sql-server database sql-server-2005


【解决方案1】:

我们可以有不同类型的转换:

  • 尝试解析

    它将字符串数据类型转换为目标数据类型(日期或数字)

这是一个例子:

Declare @fakeDate as varchar(10);
Declare @realDate as varchar(10);
set @fakeDate = 'I am not a date';
set @realdate = '13/09/2015';

select try_parse (@fakeDate as DATE); --Null  because the parsing fails
select try_parse (@realDate as DATE); --Null due to type mismatch
select try_parse (@realDate as DATE using 'FR-FR'); --13/09/2015
  • 尝试转换

它将值转换为指定的数据类型,如果转换失败返回NULL 语法是:

try_convert(data_type[(length)], expression[,style])
  • 转换

它将表达式从一种类型转换为另一种类型, 一个例子是:

select convert(varchar(20),GetDate,108);

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    不要使用上午下午:

    选择转换(日期时间,'06-07-2019 23:59:00')

    【讨论】:

    • 我得到了答案,这是超出范围的问题,因为在月份字段中我是过去的一年。它没有在 2 位空间中累积 4 位。
    【解决方案3】:

    在查询中将日期从 dd-MM 格式更改为 MM-dd 格式

    convert(datetime,'06-30-2019 00:00:00 AM')
    

    【讨论】:

    • 或者更好:将其转换为 ISO-8601 格式:20190630 - 然后它会无论您的语言/区域设置如何是!
    • 我得到了答案,这是超出范围的问题,因为在月份字段中我是过去的一年。它没有在 2 位空间中累积 4 位。
    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    相关资源
    最近更新 更多