I am using MS SQL Server and I have a table named Logs
that looks like this:
Records are added frequently so the table becomes quite big after few days/weeks.
I need to perform a little cleanup periodically: I need query that would delete older rows and keep only the most recent 100 rows in the table.
I understand it would have been better to have it delete records older than some date... but I am asked to do it as described above.
5条答案
按热度按时间rbpvctlc1#
You can use one of the following:
kg7wmglp2#
While I agree with others that this is probably not the way to go, here's a way to do it anyway:
axkjgtzd3#
Instead of using
NOT EXISTS
, just use>=
:I'm not sure if there are lock settings where new rows could be added in while the
delete
is running. If so, this would still be safe for that.You can actually simplify this in SQL Server 2012+:
kyxcudwk4#
vqlkdk9b5#
This works for me: