从日期时间转换为 INT

问题描述 投票:0回答:4

在我的 SSIS 包中,我必须将值从 DateTime 转换为相应的 INTEGER 值。已提供以下示例。

关于如何转换这些有什么想法吗?

DATETIME   INT
---------  ----
1/1/2009   39814
2/1/2009   39845
3/1/2009   39873
4/1/2009   39904
5/1/2009   39934
6/1/2009   39965
7/1/2009   39995
8/1/2009   40026
9/1/2009   40057
10/1/2009  40087
11/1/2009  40118
12/1/2009  40148
1/1/2010   40179
2/1/2010   40210
3/1/2010   40238
4/1/2010   40269
5/1/2010   40299
6/1/2010   40330
sql-server ssis sql-server-2008-r2
4个回答
21
投票

编辑:在最新版本的 SQL Server 中,转换为 float/int 不再有效。请改用以下内容:

select datediff(day, '1899-12-30T00:00:00', my_date_field)
from mytable

请注意,字符串日期应采用“明确的日期格式”,这样它就不会受到服务器区域设置的影响。


在旧版本的 SQL Server 中,您可以通过先转换为浮点数再转换为 int 将 DateTime 转换为 Integer:

select cast(cast(my_date_field as float) as int) from mytable

(注意:您不能直接转换为 int,因为如果您过了中午,MSSQL 会将值向上舍入!)

如果您的数据中有偏移,您显然可以从结果中添加或减去该偏移

您可以通过直接向后投射来向另一个方向进行转换:

select cast(my_integer_date as datetime) from mytable
    

10
投票
选择 DATEDIFF(dd, '12/30/1899', mydatefield)


0
投票
或者,一旦它已经在 SSIS 中,您可以使用以下方法创建派生列(作为某些数据流任务的一部分):

(DT_I8)FLOOR((DT_R8)systemDateTime)

但是你必须进行测试才能仔细检查。


0
投票
如果您想转换为

int

 并且您知道日期的样式,例如这里 
104
 代表 
01.12.2024
,那么您可以使用 
2024-12-01
 转换为默认日期格式 
convert(date, my_date, 104)
,如下所示a 
char(10)
,然后将 
'-'
 替换为 
''
,使其成为 
int

my_date = '01.12.2024' convert(int, replace(convert(char(10),convert(date, my_date, 104)), '-',''))
    
© www.soinside.com 2019 - 2024. All rights reserved.