SQL UPDATE TOP with ORDER BY?

后端 未结 3 2095
长发绾君心
长发绾君心 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 04:44

    the correct syntax of update is

    UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]
    
    0 讨论(0)
  • 2020-12-06 05:06

    You can try sub query like

      UPDATE Messages 
        SET    status = 'P' 
        WHERE MessageId IN (SELECT TOP (@MaxRecords) MessageId FROM Messages where Status = 'N' and InsertDate >= GETDATE() ORDER BY Priority)
    output inserted.*
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题