Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the addition operator defined for DATETIME values but not for DATE?

I am aware that the workaround is to use DATEADD for both data types. I'd like to understand why the language designers chose to define this operator for one data type but not the other?

When you try using the plus operator directly on a DATE

DECLARE @tomorrow DATE = CONVERT(DATE, GETDATE()) + 1

you get this error message:

Msg 206, Level 16, State 2, Line 1
Operand type clash: date is incompatible with int

However you can add an integer to a DATETIME, and you can implicitly convert that DATETIME to a DATE with no errors:

DECLARE @thisTimeTomorrow DATETIME = GETDATE() + 1
DECLARE @tomorrow DATE = GETDATE() + 1
like image 231
Anthony Faull Avatar asked Apr 17 '15 09:04

Anthony Faull


1 Answers

This is because SQL Server DATETIME behaviour is kept the same for compatibility purposes. Since version 2008 DATETIME2 was introduced, that prohibits the ability to add integers, DATE was also introduced at the same time, and this also prohibits addition.

The simplest solution would be to move the addition inside the CONVERT:

DECLARE @tomorrow DATE = CONVERT(DATE, GETDATE()+1)

Although I would reccomend using DATEADD rather using integer additions:

DECLARE @tomorrow DATE = CONVERT(DATE, DATEADD(DD,+1,GETDATE()))

Thanks.

like image 138
John Bell Avatar answered Sep 28 '22 09:09

John Bell