【问题标题】:Wrong conversion to datetime in SQL ServerSQL Server 中的日期时间转换错误
【发布时间】:2017-11-01 18:43:54
【问题描述】:

在 Excel 中,当我将这些“常规”数字转换为日期时,我得到的数字与我在 SQL Server 中 CONVERT() 时得到的数字不同。数据来自导入。

General     Excel conversion to date       SQL Server conversion to datetime
37621       31-12-2002                     2003-01-02 00:00:00.000
39082       31-12-2006                     2007-01-02 00:00:00.000
39447       31-12-2007                     2008-01-02 00:00:00.000
etc.

如何通过 SQL Server 中的查询获得 Excel 中的真实日期?如前所述,我已经使用了CONVERT(datetime, [General]),但随后我得到了 SQL Server 转换为日期时间列中的结果。

【问题讨论】:

  • 您在 SQL Server 中使用的convert() 代码是什么?还有数据是从哪里来的?一张桌子?进口?
  • Excel/Windows 和 SQL Server 具有不同的 Day-Zeroes。过两天。 IIRC,这是 Windows V1 中的一个原始错误(我怀疑它实际上是两个不同的错误组合)。

标签: sql-server datetime sql-convert


【解决方案1】:

将 Excel 值转换为日期

Select DateAdd(DAY,General,'1899-12-30')
 From  YourTable

演示

Declare @YourTable Table ([General] int,[Excel conversion to date] varchar(50))
Insert Into @YourTable Values
 (37621,'31-12-2002')
,(39082,'31-12-2006')
,(39447,'31-12-2007')

Select *
      ,DateAdd(DAY,[General],'1899-12-30') 
from @YourTable

退货

General Excel conversion to date    (No column name)
37621   31-12-2002                  2002-12-31 00:00:00.000
39082   31-12-2006                  2006-12-31 00:00:00.000
39447   31-12-2007                  2007-12-31 00:00:00.000

【讨论】:

  • 约翰,感谢您的回答。但是当我使用上面的 SELECT 语句时,它似乎对我不起作用..我只需要用我的真实列名替换 'General' 对吗?
  • @PRIME 正确。这是为了演示如何通过 DateAdd() 将 Excel 日期值转换为 SQL Server 日期
  • @JohnCappelletti 为什么是 1899-12-30?
  • @JohnCappelletti 谢谢。这很有趣。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2019-08-03
  • 2017-06-27
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多