如何在 SQL Server 中查询大于某个日期的所有日期?

2021-12-11 00:00:00 datetime sql sql-server

我正在尝试:

SELECT * 
FROM dbo.March2010 A
WHERE A.Date >= 2010-04-01;

A.Date 看起来像:2010-03-04 00:00:00.000

然而,这是行不通的.

任何人都可以提供参考原因吗?

Can anyone provide a reference for why?

推荐答案

select *  
from dbo.March2010 A 
where A.Date >= Convert(datetime, '2010-04-01' )

在您的查询中,2010-4-01 被视为数学表达式,因此本质上它读取

In your query, 2010-4-01 is treated as a mathematical expression, so in essence it read

select *  
from dbo.March2010 A 
where A.Date >= 2005; 

(2010减4减1是2005将其转换为适当的 datetime,并使用单引号将解决此问题.)

(2010 minus 4 minus 1 is 2005 Converting it to a proper datetime, and using single quotes will fix this issue.)

从技术上讲,解析器可能会让你逃脱

Technically, the parser might allow you to get away with

select *  
from dbo.March2010 A 
where A.Date >= '2010-04-01'

它会为您进行转换,但在我看来,它不如为您之后的维护程序员显式转换为 DateTime 更具可读性.

it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime for the maintenance programmer that will come after you.

相关文章