Updating existing rows
In all previous examples, we have used INSERT commands to add new inventory rows. Now we need to consider how our system will behave if we allow UPDATEs of existing rows in the inventory trail for a given item. First of all, let's add another history of changes for item #2.
Suppose it is discovered that the initial inventory
for item #2, entered on January 1st, 2010, should have reflected a
quantity of 3, rather than 5, so we need to decrease the amount added
for that item.
This UPDATE fails, which is good news, otherwise the CurrentQuantity for any subsequent row in the history trail would be incorrect.
The correct way to UPDATE a row is to
include all the downstream ramifications of the change in one command.
In other words, if we need to modify the initial inventory entry, then
we need to make sure that, at the same time, we correctly adjust all
subsequent entries in the history trail for that item. In this case,
this will mean updating three rows all at once.
The UPDATE in Listing 21
still fails, because decreasing the original inventory from 5 to 3
means that the final modification on January 5th, 2010 would lead to a
negative value of CurrentQuantity.
If we set @fixAmount to a valid amount, –1 instead of –2, and then rerun Listing 19 it will complete successfully. We can also set @fixAmount to a positive number, run the listing again, and see that again it succeeds, as it should.
Although we have now managed,
with some difficulty, to modify a row in the middle of a history trail,
we need to emphasize that only inserting rows at the end of history
trail is fast and convenient. Correcting history is harder and may be
significantly less performant. However, our solution has dramatically
simplified and speeded up the most common operation, namely inserting
rows at the end of history trails.