简体   繁体   English

操作数类型冲突:date与dateadd中的int不兼容

[英]Operand type clash: date is incompatible with int in dateadd

The following query works: 以下查询有效:

select dateadd(m, -5, getdate() - datepart(d, getdate()) + 1)

But when I tried to replace the getdate() with a specific date, example below: 但是,当我尝试用特定日期替换getdate()时,下面的示例:

select dateadd(m, -5, (convert(DATE,'2017-01-04') - (datepart(d, getdate()) + 1)))

I get the error saying Operand type clash: date is incompatible with int 我收到错误消息,指出Operand type clash: date is incompatible with int

What did I do wrong? 我做错了什么?

It is because GETDATE() returns DATETIME datatype ,You Can do -1 or +1 with Datetime values but not with Date values. 这是因为GETDATE()返回DATETIME数据类型,您可以对Datetime值执行-1+1 ,而对Date值则不能。

If you just changed your query a little bit , convert to datetime instead of Date it will work fine. 如果您只是稍微更改了查询,将其转换为datetime而不是Date它将可以正常工作。

select dateadd(   m
               , -5
               , (convert(DATETIME,'2017-01-04') - (datepart(d, getdate()) + 1))) 

                              ^-- Datetime instead of Date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM