Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
sql where子句问题的日期早于5年_Sql_Sql Server_Tsql - Fatal编程技术网

sql where子句问题的日期早于5年

sql where子句问题的日期早于5年,sql,sql-server,tsql,Sql,Sql Server,Tsql,我如何不包括从今天起出生日期超过5年的人?这就是我所拥有的,我只是不知道如何把它放在我的where子句中 SELECT firstname, lastname, age, gender, birthdate FROM Person WHERE ... ... ... 我将使用: dateadd(year,-5, getdate()) >= birthdate 最好的方法是: where birthdate <= dateadd(year, -5, getdate()) 这是最好

我如何不包括从今天起出生日期超过5年的人?这就是我所拥有的,我只是不知道如何把它放在我的where子句中

SELECT firstname, lastname, age, gender, birthdate
FROM Person
WHERE ... ... ...
我将使用:

dateadd(year,-5, getdate()) >= birthdate

最好的方法是:

where birthdate <= dateadd(year, -5, getdate())
这是最好的原因,因为所有操作都是在非列值getdate而不是birthdate上进行的。这允许引擎在处理此where子句时利用生日索引。

使用DATEADD从今天的日期减去5年:

SELECT firstname, lastname, age, gender, birthdate
FROM Person
WHERE ... ... ...
 SELECT firstname, lastname, age, gender, birthdate
   FROM Person
  WHERE birthdate < DATEADD(year, -5, GETDATE())

@弗里安。子时间不是SQL Server函数。问题被标记为tsql。+1我认为这种情况比使用DATEDIFF更快。在这种情况下,MSSQL可以在出生日期使用索引。@Andrew Bickerton-谢谢。我真的很感激。对于提出建议的所有其他人,谢谢。imho这不允许使用索引,是吗?因为getdate不是常量。@DrCopyPaste。在getdate上没有索引。你会有一个关于生日的索引。是的,很明显!谢谢很好,我们澄清了,不知怎的,我被你的措辞弄糊涂了,对不起:D