为什么我的 WHERE 子句不能将字段识别为日期,即使已将该字段从 int 转换为 date?

Why doesn't my WHERE clause recognize field as date, even after having converted this field from int to date?

我在 SQL 服务器中做了以下 SELECT 语句,这给了我错误:

Arithmetic overflow error converting expression to data type datetime.

SELECT Id, CAST(CAST(CalendarDate as varchar(10)) as date)
FROM dbo.Sales
WHERE CalendarDate BETWEEN dateadd(month,-6, GETDATE()) AND (GETDATE())

Id =唯一标识符

CalendarDate = int,我需要将其转换为日期。

我做错了什么?

我想找到今天和 6 个月前的所有日期,但是我得到了提到的错误。

感谢任何帮助。

谢谢。

尝试像这样转换 WHERE 子句中的日期边框:

SELECT Id, CAST(CAST(CalendarDate as varchar(10)) as date)
FROM dbo.Sales
WHERE CalendarDate BETWEEN CAST(CONVERT(CHAR(8),dateadd(month,-6, GETDATE()),112)  AS INT) and CAST(CONVERT(CHAR(8),GETDATE(),112) AS INT)

因为 Where 子句在 select 子句之前计算,因此转换后的字段不被识别,因为它尚不存在。

基于 https://docs.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-ver15#logical-processing-order-of-the-select-statement ,查询的评估顺序如下:

Logical Processing Order of the SELECT statement The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. The actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP