Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 321
bala3569 Avatar asked Feb 10 '11 06:02

bala3569


People also ask

Can you compare DateTime in SQL?

The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".

How can I compare the difference between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How can I compare date and DateTime in SQL Server?

To filter a table on a DATETIME column comparing only the date part, use CAST() only around the parameter, and >= and < with the desired date and the day after.

Can DateTime be compared?

The DateTime. Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2.


1 Answers

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.

IF ( @schedule_date <= GETDATE() )
BEGIN
  RAISERROR('Schedule date should not be earlier than system date', 16, 1)
  RETURN
END
like image 91
Derek Flenniken Avatar answered Sep 29 '22 19:09

Derek Flenniken