Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can integer be subtracted from DATETIME but not DATE type

Is the relationship between DATETIME & INTEGER and DATE & INTEGER consistent?

This executes fine:

DECLARE @Yesterday DATETIME = GETDATE();
SELECT @Yesterday-1;

As does this:

DECLARE @Yesterday DATE = GETDATE();
SELECT @Yesterday;

This errors:

DECLARE @Yesterday DATE = GETDATE();
SELECT @Yesterday-1;

I can safely subtract an integer type from a datetime but not from a date.
What is the reason for this behaviour?

like image 703
whytheq Avatar asked Mar 22 '13 12:03

whytheq


2 Answers

Actually, it is very consistent. DATETIME is a type inherited from previous editions of sql server. Since 2008 edition, DATETIME2 has been introduced, and possibility of adding/subtracting integers removed. You can still do it on DATETIME as a legacy.

DATE, like DATETIME2 had been around since 2008, too, and for this type adding/subtracting numbers is also prohibited.

This gives you an error:

DECLARE @Yesterday DATETIME2 = GETDATE();
SELECT @Yesterday-1;

So everything's fine :).

like image 86
AdamL Avatar answered Nov 14 '22 22:11

AdamL


So this might be better:

declare @Yesterday DATE = DATEADD(d, -1, getdate())
select @Yesterday
like image 24
Netricity Avatar answered Nov 14 '22 23:11

Netricity