Adding rows out of date order
At the moment, our inventory system robustly handles
the insertion of new rows to the end of the inventory (i.e. in date
order). However, far more complex is the situation where we need to
insert a row when it is not the last in the trail history. It requires
two actions:
Both inserting and updating need to be done in a single command, so we need to use MERGE. The MERGE which gets the job done is quite complex and is shown in Listing 22.
This code handles inserting rows before the first
date, inbetween dates, and after the last date. More importantly, it
will also handle the case when there is already a row with the same ItemID and ChangeDate,
automatically modifying that row (and all "later" rows for the same
item) to reflect the new net change, which is computed as the old change
plus the new change. Finally, it will also automatically delete a row
if the new net change equals zero (no change).
As we have seen, modifying
anywhere other than in the very end of a history trail may be quite
involved, but the integrity of our data is never compromised. In many
cases, such as inventory systems, this complexity of modifications in
the middle of a history is perfectly acceptable, because under normal
circumstances we just never need to do it. However, this approach is not
for everyone; we need to decide whether to use it on a case-by-case
basis.