【发布时间】:2019-10-09 03:24:17
【问题描述】:
我在 SQL Server 引发错误的查询中遇到问题
无法构造数据类型日期,某些参数的值无效
比较两个本身有效的日期对象时。
如果我删除 where 子句,它会正确解析,但当我尝试将它们与任何关系或相等运算符进行比较时,它会再次出错。
重现问题的最小查询如下:
with Years as
(
select
YEAR(getdate()) + 1 Year,
DATEFROMPARTS(YEAR(getdate()) + 1, 1, 1) FirstOfTheYear,
0 YearOffset
union all
select
Year - 1,
DATEFROMPARTS(Year - 1, 1, 1),
YearOffset + 1
from Years
where YearOffset < 5
),
Months as
(
select 1 Month
union all
select Month + 1
from Months
where Month < 12
),
Days as
(
select 1 Day
union all
select Day + 1
from Days
where Day < 31
),
Dates as
(
select cast(DATEFROMPARTS(Year, Month, Day) as date) Date
from Years
cross join Months
cross join Days
where DAY(EOMONTH(FirstOfTheYear, Month - 1)) >= Day
)
select Dates.Date, cast ('2019-10-01' as date), CAST ('2019-10-11' as date)
from Dates
where Date = cast ('2019-10-01' as date) -- Comment this line out and the error goes away, occurs with any date construction pattern
--where Dates.[Date] >= datefromparts(2019, 10, 01) and Dates.[Date] <= DATEFROMPARTS(2019, 10, 11)
order by date
注释掉 where 子句按预期返回结果,确认正是比较触发了这个问题。
此外,手动创建一些日期(2015-2019 年的第一天,查询中的 10 月日期)并针对这些日期进行查询不会导致显示错误。
编辑:我想强调代码已经正确处理了二月和闰年。 Dates CTE 的输出是有效的,并且输出完整的范围而没有错误。 只有当我在 where 子句中引用日期时会引发错误
Edit2:我能够通过切换到不同的日期生成模式(以递归方式添加一天、一天一天)来解决我的问题,但我仍然很好奇导致此错误的原因。
【问题讨论】:
标签: sql sql-server date