Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update and order by using ms sql

Ideally I want to do this:

UPDATE TOP (10) messages SET status=10 WHERE status=0 ORDER BY priority DESC; 

In English: I want to get the top 10 available (status=0) messages from the DB and lock them (status=10). A message with a higher priority should be gotten first.

unfortunately MS SQL doesn't allow an order by clause in the update.

Anyway how to circumvent this?

like image 794
Toad Avatar asked Mar 17 '09 16:03

Toad


People also ask

Can I use update and ORDER BY in SQL?

You Can Use ORDER BY And LIMIT Within UPDATE And DELETE Statements In MySQL 5.6.

Can ORDER BY BE USED IN update?

unfortunately MS SQL doesn't allow an order by clause in the update.

Can we use ORDER BY clause in update statement?

If an UPDATE statement includes an ORDER BY clause, the rows are updated in the order specified by the clause. This can be useful in certain situations that might otherwise result in an error.


1 Answers

WITH    q AS         (         SELECT  TOP 10 *         FROM    messages         WHERE   status = 0         ORDER BY                 priority DESC         ) UPDATE  q SET     status = 10 
like image 92
Quassnoi Avatar answered Sep 17 '22 14:09

Quassnoi