SQL Server: How to get rows where the date is older than X years?

eyh26e7m  于 2022-12-22  发布在  SQL Server
关注(0)|答案(5)|浏览(111)

Question

I would like to pull all assets from a database which is a certain amount of years old, in this case years. Is this statement correct?

Background

The database is called AssetRegister
The table is called dbo.Assets
the column is called AcquiredDate

Statement so far

SELECT * FROM dbo.Assets WHERE AcquiredDate < '2008-01-01'
4szc88ey

4szc88ey1#

SELECT * FROM dbo.Assets                  
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8

For an performance optimized query look at @Horaciuxs answer.

wvyml7n5

wvyml7n52#

The answer by @Juergen bring the right results:

SELECT * FROM dbo.Assets                  
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8

But, the SQL optimizer can't use an index on AcquiredDate, even if one exists. It will literally have to evaluate this function for every row of the table.
For big tables is recommended to use:

DECLARE @limitDate Date
SELECT @limitDate=DATEADD(year,-8,GETDATE()) --Calculate limit date 8 year before now.

SELECT * FROM dbo.Assets                  
WHERE AcquiredDate <= @limitDate

Or simply:

SELECT * FROM dbo.Assets                  
    WHERE AcquiredDate <= DATEADD(year,-8,GETDATE())
xxls0lw8

xxls0lw83#

SELECT * FROM dbo.Assets WHERE AcquiredDate >= '2006-01-01'

SELECT * FROM dbo.Assets WHERE AcquiredDate >= (year(getdate()) - 8)
l0oc07j2

l0oc07j24#

CAREFUL - DATEDIFF only looks at year. Consider this query:

SELECT DATEDIFF(year,'2012-10-01','2022-06-01')

clearly the date is 9 years 8 months old but the query returns 10. So if you are deleting records >= 10 years old based on this kind of query you're in a fix....

Better to use something like this as highlighted by @Horaciux

WHERE dt > DATEADD(YEAR,-10,'20220501')
aemubtdh

aemubtdh5#

SELECT * FROM dbo.Assets 
 WHERE YEAR(AcquiredDate) < 2008

The solution posted by juergen d and Ankit are better, but if you want to compare the Year, you can use the YEAR function.

相关问题