首页 > 解决方案 > 错误消息:“消息 206,级别 16,状态 2,第 1 行操作数类型冲突:int 与日期不兼容”

问题描述

我想将它从日期时间转换为日期数据类型。有人可以回答这个吗?谢谢。

select 

(case when (t0.InvType = '13') then (select (cast(DocDate as date)) from OINV 
where DocEntry = t0.DocEntry and t0.InvType = '13'))

     when t0.InvType = '18' then (select (cast(DocDate as date)) from OPCH where DocEntry = t0.DocEntry and t0.InvType = '18')
      when t0.InvType = '19' then (select (cast(DocDate as date)) from ORPC where DocEntry = t0.DocEntry and t0.InvType = '19')
      when t0.InvType = '204' then (select (cast(DocDate as date)) from ODPO where DocEntry = t0.DocEntry and t0.InvType = '204')
      when t0.InvType = '30' then (select (cast(DocDate as date)) from OJDT where TransId = t0.DocEntry and t0.InvType = '30')
      else 0
            end) as MonthQ

标签: sql-serversql-server-2012

解决方案


就像错误所说的数据类型int与数据类型不兼容date。事实上,数值不能与任何“新”数据/时间数据类型一起使用(“新”是指 SQL Server 2008 引入的数据类型,例如datetime2, datetimeoffset, date)。

datetime但是,它是兼容的,但建议您在新应用程序中使用datetime2over datetime。但是,如果您需要将数字转换为 adate您需要先将其转换为 a datetime,或者DATEADD 改为使用。

datetime,以前所0代表的日期'1900-01-01'。所以,而不是CONVERT(date,DocDate)你需要做DATEADD(DAY, DocDate , '19000101').

相反,您也可以使用CONVERT(date, CONVERT(datetime,DocDate)),但进行 2 次转换似乎很愚蠢。


推荐阅读