I have a table with an OrderSequence
column. The schema looks roughly like this:
id
Name
OrderSequence
I have an array of ids ["1", "2", "3", "4"] from an application, and I want to set the OrderSequence
for sorting purposes. I don't want to loop through the rows from the application, executing 'n' SQL queries one at a time. How can I do this using a stored procedure?
Sample data
id Name OrderSequence
1 A 0
2 B 0
3 C 0
Desired result
id Name OrderSequence
1 A 1
2 B 2
3 C 3
Best Answer
You can accomplish this using
ROW_NUMBER()
syntax, as mentioned by @Kin :Output:
If you want only update certain rows, you can use a Table Variable (or a #temp table if you are updating a LOT of rows), as such:
The example above results in the following output:
An improvement (based on a suggestion by Daniel Hutmacher) avoids the join and results in a more efficient query plan (no join or Halloween protection):
Or, when using the
@IDsToUpdate
table: