Rhino wrote:
You can't update the primary key of a table directly. This is due to the
possibility that your update will affect potentially millions of rows in
dependent tables whose foreign key is the same as the primary key you are
changing.
To change a primary key, you need to:
1. INSERT a new row that has the desired key
2. UPDATE all the foreign keys that refer to the old primary key value to
the new value
3. DELETE the old primary key
Well, that's not quite correct. Of course you can update the values of a
primary key column (unless you have an MPP system and the column in
question is part of the partitioning key). What you can't do, however, is
updating a value of a primary or unique key if there are dependent records
for the value to be updated. The reason is that DB2 does not yet support
ON UPDATE CASCADE for foreign key relationships.
If your foreign key (FK) is defined as ON UPDATE NO ACTION, then the update
will succeed if the result of the update does not violate the FK. If the
FX is defined as ON UPDATE RESTRICT, then you can't update the value if
there is any dependent row.
To clarify the difference between NO ACTION and RESTRICT, the following
works in the first case and is rejected in the second:
CREATE TABLE t1 ( c1 INT NOT NULL PRIMARY KEY )
CREATE TABLE t2 ( c1 INT FOREIGN KEY REFERENCES t1 ON UPDATE NO ACTION )
INSERT INTO t1 VALUES (1), (2), (3)
INSERT INTO t2 VALUES (2), (3)
-- this works with NO ACTION and fails with RESTRICT
UPDATE t1 SET c1 = c1+1
Another option is to not use foreign keys at all and to implement a bunch of
triggers for each FK instead. Then you can handle the cascading update in
the trigger. However, I wouldn't really recommend such an approach because
it gets really messy really fast.
--
Knut Stolze
Information Integration
IBM Germany / University of Jena