为什么为DATETIME值而不是DATE定义加法运算符? [英] Why is the addition operator defined for DATETIME values but not for DATE?

查看:87
本文介绍了为什么为DATETIME值而不是DATE定义加法运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道解决方法是对两种数据类型使用 DATEADD 。我想了解为什么语言设计师选择为一种数据类型而不是为另一种数据类型定义此运算符?

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?

当您尝试直接在 DATE

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

您会收到以下错误消息:

you get this error message:

消息206,级别16,状态2,第1行

操作数类型冲突:日期与int不兼容

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

不过,您可以将整数添加到 DATETIME ,并且可以隐式转换该 DATETIME DATE 且没有错误:

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


推荐答案

这是因为出于兼容性目的,SQL Server DATETIME行为保持不变。自从引入了禁止添加整数功能的2008版本DATETIME2以来,DATE同时被引入了,这也禁止了加法运算。

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.

最简单的解决方案是将加法运算转换为CONVERT:

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

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

尽管我建议使用DATEADD而不是使用整数加法运算:

Although I would reccomend using DATEADD rather using integer additions:

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

谢谢。

这篇关于为什么为DATETIME值而不是DATE定义加法运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆