SQL UPDATE TOP with ORDER BY?

后端 未结 3 2101
长发绾君心
长发绾君心 2020-12-06 04:30

I have a following query:

UPDATE TOP (@MaxRecords) Messages 
SET    status = \'P\' 
OUTPUT inserted.* 
FROM   Messages 
where Status = \'N\'
and InsertDate &         


        
3条回答
  •  情深已故
    2020-12-06 05:07

    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.

提交回复
热议问题