Why can integer be subtracted from DATETIME but not DATE type

被刻印的时光 ゝ 提交于 2020-01-03 08:41:35

问题


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?


回答1:


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 :).




回答2:


So this might be better:

declare @Yesterday DATE = DATEADD(d, -1, getdate())
select @Yesterday


来源:https://stackoverflow.com/questions/15569817/why-can-integer-be-subtracted-from-datetime-but-not-date-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!