I have a following query:
UPDATE TOP (@MaxRecords) Messages SET status = 'P' OUTPUT inserted.* FROM Messages where Status = 'N' and InsertDate >= GETDATE()
In the Messages table there is priority column and I want to select high priority messages first. So I need an ORDER BY. But I do not need to have sorted output but sorted data before update runs.
As far as I know it's not possible to add ORDER BY to UPDATE statement. Any other ideas?
UPDATE t SET id = id + 1 ORDER BY id DESC; You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BY or LIMIT with a multiple-table UPDATE .
Without the TOP clause, if you are doing a manual update and your mouse text selection only selects from "UPDATE" to just before the "WHERE" clause, then the update is applied to ALL rows. With the TOP clause, only one row would get the undesired update.
You Can Use ORDER BY And LIMIT Within UPDATE And DELETE Statements In MySQL 5.6.
Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group.
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.
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.*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With