SQL UPDATE TOP with ORDER BY?

you can use common table expression for this:

;with cte as (
   select top (@MaxRecords)
       status
   from Messages 
   where Status="N" and InsertDate >= getdate()
   order by ...
)
update cte set
    status="P"
output inserted.*

This one uses the fact that in SQL Server it’s possible to update cte, like updatable view.

Leave a Comment