我从这段代码中得到以下错误
Msg 242,Level 16,State 3,Line 3
将varchar数据类型转换为日期时间数据类型会导致超出范围的值。
T-SQL:
datediff(dd, a.ContractStartDate,
cast(case when isdate(
cast(datepart(month, dateadd(mm, 0, a.WarrStartDate)) as varchar(2)) + '/' +
cast('00' + datepart(DAY, a.WarrStartDate) as varchar(2)) + '/' +
cast(datepart(year, dateadd(YEAR, case when a.TRSCustNO = 89555 then 2 else 3 end, a.WarrStartDate)) as varchar(4)))=0
then
cast('00'+datepart(month,dateadd(mm,0,a.WarrStartDate))as varchar(2))+'/'+
cast('00'+datepart(DAY,dateadd(dd,-1,a.WarrStartDate)) as varchar(2)) +'/'+
cast(datepart(year,dateadd(YEAR,case when a.TRSCustNO = 89555 then 2 else 3 end
,a.WarrStartDate))as varchar(4))
else
cast('00'+datepart(month,dateadd(mm,0,a.WarrStartDate))as varchar(2))+'/'+
cast('00'+datepart(DAY,a.WarrStartDate) as varchar(2)) +'/'+
cast(datepart(year,dateadd(YEAR,case when a.TRSCustNO = 89555 then 2 else 3 end
,a.WarrStartDate))as varchar(4)
) end
as datetime)
) as EarnDays
答案 0 :(得分:0)
除非我遗漏了什么,否则这一切都可以简化。我没有看到在date和varchar类型之间进行转换的原因。
case
when datediff(dd,a.ContractStartDate,
dateadd(year,(case when a.TRSCustNO = 89555 then 2 else 3 end), a.WarrStartDate)
)=0
then
dateadd(year, (case when a.TRSCustNO = 89555 then 2 else 3 end),
dateadd(dd,-1,a.WarrStartDate)
)
else
dateadd(year, (case when a.TRSCustNO = 89555 then 2 else 3 end), a.WarrStartDate)
end as EarnDays
如果我错过了它,请告诉我。
如果您想知道为什么会收到错误,请不要将其转回日期并查看输出。