如何在mssql中检查epoch datetime的日期范围

时间:2012-07-12 09:48:54

标签: sql-server-2008 sql-server-2005

在其中一个表中,日期列值如下所示

 date
25052008112228
26052008062717

表名是事务

我尝试使用以下查询但其抛出错误

select * from transaction where date between '2012-01-06' and '2012-06-30'

select * from transaction where date between '2012/01/06' and '2012/06/30'

给我一​​个解决方案。

2 个答案:

答案 0 :(得分:0)

- asp时间戳

 select  * from [transaction] where 
    cast(SUBSTRING([date],5,4) + '-' + SUBSTRING([date],3,2) + '-' +
    SUBSTRING([date],1,2) + ' ' + SUBSTRING([date],9,2) + 
    ':' + SUBSTRING([date],11,2) + ':' +
    SUBSTRING([date],13,2) as datetime)
between '2008-05-26' and  '2012-01-06'

- unix纪元时间

 select * from [transaction] where  [date] 
 between DATEDIFF( SECOND, '01-01-1970 00:00:00', '2012-01-06' ) 
 and DATEDIFF( SECOND, '01-01-1970 00:00:00', '2012-06-30')

答案 1 :(得分:0)

问题是[date]列不包含将自动转换为适当datetime值的格式的日期 - 它甚至不包含支持的格式值。所以你要使用字符串操作粉碎文本:

declare @Transactions table (TDate char(14))
insert into @Transactions (TDate) values
('25052008112228'),
('26052008062717')

select CONVERT(datetime,
    SUBSTRING(TDate,5,4) + '-' +
    SUBSTRING(TDate,3,2) + '-' +
    SUBSTRING(TDate,1,2) + 'T' +
    SUBSTRING(TDate,9,2) + ':' +
    SUBSTRING(TDate,11,2) + ':' +
    SUBSTRING(TDate,13,2))
from
    @Transactions

结果:

2008-05-25 11:22:28.000
2008-05-26 06:27:17.000

如果您需要经常执行此类转换,可以将CONVERT/SUBSTRING操作包装到UDF中。当然,理想的做法是更改列定义以存储真正的datetime值 - 当人们将其视为文本时,几乎所有datetime问题都会出现。

(注意,我已经重命名了表格和列,因为使用保留字通常是个坏主意)


您的查询可能类似于:

;with converted as (
     select *,CONVERT(datetime,
            SUBSTRING([Date],5,4) + '-' +
            SUBSTRING([Date],3,2) + '-' +
        SUBSTRING([Date],1,2) + 'T' +
        SUBSTRING([Date],9,2) + ':' +
        SUBSTRING([Date],11,2) + ':' +
        SUBSTRING([Date],13,2)) as GenuineDate
     from [Transaction]
)
select * from converted where GenuineDate between '20120106' and '20120630'

(请注意,我还将最终查询中的日期文字也更改为安全格式)