The data types date and datetime are incompatible in the add operator

六眼飞鱼酱① 提交于 2019-12-11 04:27:37

问题


I recently created in a SQL Server 2008 dev environment a function that concatenates a date and time like this

select cast('2016-11-09 15:35:00' AS DATE) + CAST('00:00:00' AS DATETIME)

In SQL Server 2008 it works well but deployed in SQL Server 2016 it throws an error

The data types date and datetime are incompatible in the add operator.

But it works well ONLY if queries are placed separately

select cast('2016-11-09 15:35:00' AS DATE)
select CAST('00:00:00' AS DATETIME)

So, how can I fix this. I found articles where people say that there is an incompatibility with TIME data type, but I am not using it. In fact, my concatenation is like this

 WHERE 
     CREATIONDATE BETWEEN CAST(@CurrentDate AS DATE) + CAST('00:00:00' AS DATETIME) AND CAST(@CurrentDate AS DATE) + CAST('23:59:59' AS DATETIME)

where @CurrentDate is a DateTime variable and passed to my function as '2016-11-09 15:35:00'

I cannot modify the configuration of the SQL Server 2016 box. How can I fix my code?

Thanks


回答1:


Just cast it as a date and then a datetime.

select cast(cast('2016-11-09 15:35:00' as date) as datetime)

To get 1 more day, use:

dateadd select dateadd(dd,1,cast(cast('2016-11-09 15:35:00' as date) as datetime))

I'm not a huge fan of the between operator so when i deal with datetimes i tend to use > startDate and < endDate where the endDate is the next day , so 11/10 which is like saying <= 11/09 23:59:59



来源:https://stackoverflow.com/questions/40514726/the-data-types-date-and-datetime-are-incompatible-in-the-add-operator

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