Question

Is there any way to update in the way that every time my Update stmt check for the max(column) value and then +1 and update the record. For example.

UPDATE MyTable
SET NEW_KEY = (SELECT MAX(KEY) + 1 FROM MyTable)
WHERE NEW_RECORD = 0;

So instead of just picking max and then set max+1 for all the records. It do it in iterations, by looking max value every time.

Was it helpful?

Solution

This can be done in one statement:

UPDATE (SELECT new_key, new_record,
               MAX(key) OVER(ORDER BY key) as minimumKey,
               COUNT() OVER(ORDER BY key ROWS UNBOUNDED PRECEDING) + 1 as offsetKey
        FROM MyTable) MyTable
SET new_key = minimumKey + offsetKey
WHERE new_record = 0;

(untested, because I don't have an LUW instance to use)
If there are rows with new_record <> 0, there will be gaps in the sequence of the new keys (my personal belief is that the actual value of a key is unimportant, so don't worry about that).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top