Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 这段代码如何在不使用DATEADD的情况下将数字添加到datetime?_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 这段代码如何在不使用DATEADD的情况下将数字添加到datetime?

Sql 这段代码如何在不使用DATEADD的情况下将数字添加到datetime?,sql,sql-server,tsql,Sql,Sql Server,Tsql,在下面的SQL语句中,有一些T-SQL将数字添加到日期时间和日期: declare @t table(UserID int, StartDate datetime, EndDate date) insert @t select 1, '20110101', '20110102' -- Adding int to a datetime works select t.StartDate + 2 as NewStartDate -- Adding int to a date errors sel

在下面的SQL语句中,有一些T-SQL将数字添加到
日期时间
日期

declare @t table(UserID int, StartDate datetime, EndDate date)
insert @t select 1, '20110101', '20110102' 

-- Adding int to a datetime works
select t.StartDate + 2 as NewStartDate

-- Adding int to a date errors
select t.EndDate + 2 as NewEndDate

我预计上述两个select语句都会失败,因为它们都没有使用
DATEADD
方法,但令我惊讶的是,在
datetime
中添加
int
而不使用
DATEADD
是有效的。为什么会这样?

您可以在日期时间中添加一个数字。它被解释为天数

也许令人惊讶的是,SQL Server不支持将整数添加到
date

因此,这是可行的:

select getdate() + 1
但这会产生一个错误:

select cast(getdate() as date) + 1
这在以下文档中进行了解释:

表情

是数值类别中任何一种数据类型(位数据类型除外)的任何有效表达式。不能与
date
time
datetime2
datetimeoffset
数据类型一起使用

我的意思是,任何阅读本文的人都会立即注意到,
datetime
属于“数值”类别,并且在不受支持的类型列表中缺失


我应该注意,此功能还允许添加两个
datetime
值。这对于将“时间”(转换为
datetime
)添加到日期(转换为
datetime
)非常方便。

您可以将数字添加到
datetime
)。它被解释为天数

也许令人惊讶的是,SQL Server不支持将整数添加到
date

因此,这是可行的:

select getdate() + 1
但这会产生一个错误:

select cast(getdate() as date) + 1
这在以下文档中进行了解释:

表情

是数值类别中任何一种数据类型(位数据类型除外)的任何有效表达式。不能与
date
time
datetime2
datetimeoffset
数据类型一起使用

我的意思是,任何阅读本文的人都会立即注意到,
datetime
属于“数值”类别,并且在不受支持的类型列表中缺失


我应该注意,此功能还允许添加两个
datetime
值。这对于将“时间”(强制转换为
datetime
)添加到日期(强制转换为
datetime
)非常方便。

Datetime2也会失败。@tomRedox列不可用Field@tomRedox这里的人总是这么说,但我觉得这充其量也太挑剔了。我不会担心的。这不是一件好事,反正只是草率的编码。始终使用DATEADD,因为可能有人决定更改数据类型,这会破坏一切。Datetime2也会失败。@tomRedox列不会Field@tomRedox这里的人总是这么说,但我觉得这充其量也太挑剔了。我不会担心的。这不是一件好事,反正只是草率的编码。始终使用DATEADD,因为可能有人决定更改数据类型,这会破坏一切。您确定您的列是
DateTime
datatype而不是
Date
?顺便说一句,没有字段是列。@Sami我现在重新编写了问题,希望能回到主题上来,如果需要进一步修改,请告诉我。你确定你的列是
DateTime
datatype而不是
Date
?顺便说一句,没有字段是列。@Sami我现在重新编写了问题,希望能回到主题上来,如果需要进一步修改,请告诉我。