简体   繁体   English

sql中的日期时间比较错误?

[英]Datetime comparison error in sql?

I have used date and time validation for scheduling a report...I have to schedule that reports for future date and time only and not previous date and time..I have used this 我已经使用日期和时间验证来安排报告......我必须安排该报告仅用于未来的日期和时间而不是之前的日期和时间..我已经使用过这个

    declare @Dt varchar(50) 
    declare @Hr varchar(50)
    declare @trandate_time_tmp as TIME(0)

    select @trandate_time_tmp = getdate()
    set @Dt = DATEDIFF (D,@schedule_date ,@trandate_tmp )
    set @Hr = DATEDIFF (S,@schedule_date ,@trandate_time_tmp )

    if ( @Dt > 0)
    begin
        raiserror('Schedule Date should not be earlier than system date',16,1)
        return
    end

    if ( @Hr > 0) 
    begin
        raiserror('Schedule Time should not be earlier than system time',16,1)
        return
    end

For date part it is checking correctly but for time it is throwing error as 对于日期部分,它正在检查正确,但是对于时间,它会抛出错误

The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.

Not exactly answering your question, but perhaps a solution to your problem. 不完全回答你的问题,但也许解决你的问题。 You don't need to use DATEDIFF and check the results, you could just compare the two dates. 您不需要使用DATEDIFF并检查结果,您可以只比较两个日期。

IF ( @schedule_date <= GETDATE() )
BEGIN
  RAISERROR('Schedule date should not be earlier than system date', 16, 1)
  RETURN
END

I just ran into this same problem when trying to make a Unix timestamp from a date, 我在尝试从日期创建Unix时间戳时遇到了同样的问题,

Here's an example of what I was trying to do: 这是我尝试做的一个例子:

select DATEDIFF(second,'1970-01-01','2200-01-11');

It overflows since DATEDIFF is trying to return a signed integer - which can only hold just over 68 years worth of seconds. 它会溢出,因为DATEDIFF试图返回一个有符号整数 - 它只能容纳超过68年的秒数。

In order to get the Unix timestamp (which I need so I can feed it into Sphinx Search), you can get the difference in minutes first, then cast the result as a big integer and then multiply by 60 seconds: 为了获得Unix时间戳(我需要这样我可以将其提供给Sphinx Search),您可以先在几分钟内获得差异,然后将结果转换为大整数,然后乘以60秒:

select CAST(DATEDIFF(minute,'1970-01-01','2200-01-11') AS BIGINT) * 60;

Now we should be able to handle dates that vary in difference of up to 4000 years or so. 现在我们应该能够处理差异长达4000年左右的日期。 If you need even more room, simply change out minute with bigger and bigger intervals, and change the seconds multiplier accordingly. 如果您需要更多空间,只需更换更大更大间隔的分钟,并相应地更改秒数乘数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM