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'
5条答案
按热度按时间4szc88ey1#
For an performance optimized query look at @Horaciuxs answer.
wvyml7n52#
The answer by @Juergen bring the right results:
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:
Or simply:
xxls0lw83#
或
l0oc07j24#
CAREFUL - DATEDIFF only looks at year. Consider this query:
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
aemubtdh5#
The solution posted by juergen d and Ankit are better, but if you want to compare the Year, you can use the YEAR function.