Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use DATEADD(), but only if year is not 9999

Tags:

sql-server

I am trying to perform a SQL query along the lines of:

SELECT * 
FROM MyTable
WHERE GETDATE() AS CurrentDateTime < DATEADD(day, 1, EndDateTime)

The issue is that some of the EndDateTime's have the highest date possible, and when I try to run this query, I get an error: Adding a value to a 'datetime' column caused an overflow.

Any idea how I can use the EndDateTime itself instead of the EndDateTime + 1 day, if the date has a year of 9999?

like image 472
Alan Schapira Avatar asked Dec 02 '25 22:12

Alan Schapira


1 Answers

Do the logic in the other order:

SELECT * 
FROM MyTable
WHERE EndDateTime > DATEADD(day, -1, GETDATE() );

This is also better because the query can take advantage of an index whose first key is EndDateTime.

like image 116
Gordon Linoff Avatar answered Dec 05 '25 13:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!