首页 > 解决方案 > 在 where 子句中使用日期检查执行查询时出错

问题描述

我有一个表,其中年份和月份值分别保存为 int 数据类型列 [Year] 和 [Month]。我需要使用 WHERE 子句查询将输出限制在某个日期的表。我想出了一个使用 DATEFROMPARTS 函数的解决方案(避免数据类型的多次转换),它在 SELECT 子句中完美运行(不同日期的数量是有限的,所以我可以检查所有这些),但是当我尝试使用时失败了WHERE 子句中的复合日期。

因此查询像

SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1) FROM MyTable 

2019-04-01
2019-05-01
2019-06-01
2019-07-01
2019-08-01
2019-09-01
2019-10-01
2019-11-01
2019-12-01
2020-01-01
2020-02-01
2020-03-01

但是当我添加一个 WHERE 子句时

SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1) FROM MyTable 
WHERE DATEFROMPARTS([Year], [Month], 1) < convert(date, getdate(), 23)

或者

SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1) FROM MyTable 
WHERE DATEFROMPARTS([Year], [MonthNumber], 1) < convert (date, '2019-12-01', 23)

我收到一个错误:

无法构造数据类型日期,某些参数的值无效。

我正在使用 SQL Server 版本。13

免责声明 数据存储在我从云计算机访问的远程 SQL 服务器上。这是一个视图,我对它的权限为零,只能在 ETL 过程中进一步阅读和使用它。Year 和 Month 列中没有非法值,例如 NULL、Month > 12 等。

更新 我在 SQL Server 2016 上尝试过类似的场景:

CREATE TABLE MyTable(
    [Year] [int] NULL,
    [Month] [int] NULL)

INSERT INTO MyTable
           ([Year], [Month])
     VALUES
          (2019, 9)
         ,(2019, 10)
         ,(2019, 11)
         ,(2019, 12)
         ,(2020, 1)
         ,(2020, 2)
         ,(2020, 3)
         ,(2020, 4)

DATEFROMPARTS 或连接 dateparts 并转换为不同格式的日期的组合不起作用,充其量,日期仅在 yyyy-mm-dd 格式下看起来不错,但无法与 getdate() 函数进行比较。

@John-Cappelletti 建议的解决方案有助于解决最初的问题:

try_convert(date, concat([Year],'/',[Month],'/', 1))

尽管我仍然不清楚为什么不能将组合日期转换为不同的日期样式。

标签: sqlsql-servertsqldate

解决方案


由于数据问题,可能try_convert()concat()

例子

Declare @YourTable Table ([Year] int,[Month] int)  
Insert Into @YourTable Values 
 (2020,1)
,(2020,1)
,(2020,2)
,(2020,222)

Select * 
      ,try_convert(date,concat([Year],'/',[Month],'/', 1))
 From @YourTable

退货

Year    Month   (No column name)
2020    1       2020-01-01
2020    1       2020-01-01
2020    2       2020-02-01
2020    222     NULL          << There's a problem

推荐阅读