我在将年、月、日的int值转换为日期值时遇到问题。
SELECT datefromparts(b.Install_year, b.shipm_month, b.shipm_day)我已经找到了这个问题的解决方案,发现DAY的一些值是0。但我很好奇为什么事情会以某种方式运作。
SELECT datefromparts(2005, 4, b.shipm_day)出于测试目的,我将年和月的值设置为固定的。将1,3,5,7,8,10,12作为月份,并在Management Studio中运行,我可以看到结果。值:2、4、6、9和11会导致以下错误:“无法构造数据类型date,某些参数的值无效。”
有人知道为什么某些价值观有效而其他价值观无效吗?
发布于 2019-11-08 01:02:05
这可能是因为"day“值是31,而这些月份没有31天。
datefromparts()仅构造有效日期。
这并不容易修复,因为datefromparts()没有"try_“版本。
以下是一种方法:
select coalesce(try_convert(date, concat(2005, '-', 4, '-', b.shipm_day)),
try_convert(date, concat(2005, '-', 4, '-', b.shipm_day - 1)),
try_convert(date, concat(2005, '-', 4, '-', b.shipm_day - 2)),
try_convert(date, concat(2005, '-', 4, '-', b.shipm_day - 3))
)https://stackoverflow.com/questions/58753672
复制相似问题