How to add a calculated (generated) column to an existing table?


Suppose we have a table we want to add a generated column like this:

CREATE TABLE abc.test (
X INTEGER not null,
Y INTEGER not null
);

 Now we want to add a new column to this table and we want the new column to have sum of column X & Y.

Before adding a generated column, table must be placed into Check Pending state, so we do this:

SET INTEGRITY FOR abc.Test OFF

While the table is in Check Pending state, it cannot be used.
Now we add a generated column:

ALTER TABLE abc.Test
ADD COLUMN TOTAL INTEGER GENERATED ALWAYS AS (X + Y)

After adding the column, the table must be brought out of check pending state (aka Set Integrity Pending State). We bring the table out of check pending state by this:

SET INTEGRITY FOR abc.Test IMMEDIATE CHECKED FORCE GENERATED

 Now if you insert values for x & y & sum will generate in the newly added column(Total)

 db2”insert into abc.Test (x,y) values(1,10)

db2 “insert into abc.Test(x,y) values(10,90)

 Output :

 X          Y          TOTAL

1          10        11

10        90        100

 




Comments

Popular posts from this blog

Db2 export command example using file format (del , ixf)

How to fix DB2 Tablespace OFFLINE state issue?

How to determine fenced User-ID of a DB2 instance