Adding a system period and system-period data versioning to an existing table
You can alter existing tables to use system-period data versioning.
About this task
A system period is a system-maintained period in which Db2 maintains the beginning and ending timestamp values for a row.
A system period temporal table has three required columns. The row-begin column of the system period contains the timestamp value for when a row is created. The row-end column contains the timestamp value for when a row is removed. A transaction-start-ID column contains a unique timestamp value that Db2 assigns per transaction, or the null value.
The null value is assigned to the transaction-start-ID column if the column is nullable. Otherwise, the value is generated using the time-of-day clock during execution of the first data change statement in the transaction that requires a value to be assigned to a row-begin column or transaction-start-ID column in the table, or when a row in a system-period temporal table is deleted. If multiple rows are inserted or updated within a single SQL transaction, the values for the transaction-start-ID column are the same for all the rows and are unique from the values that are generated for the column for another transaction.
Procedure
To add a system period to a table and define system-period data versioning:
Example
For example, consider that
you created a table named policy_info by issuing the following CREATE
TABLE statement:
CREATE TABLE policy_info
(policy_id CHAR(10) NOT NULL,
coverage INT NOT NULL);
Issue the following ALTER TABLE statements to add the begin and end columns and a system period to the table:
ALTER TABLE policy_info ADD COLUMN sys_start TIMESTAMP(12) NOT NULL
GENERATED ALWAYS AS ROW BEGIN;
ALTER TABLE policy_info ADD COLUMN sys_end TIMESTAMP(12) NOT NULL
GENERATED ALWAYS AS ROW END;
ALTER TABLE policy_info ADD COLUMN trans_id TIMESTAMP(12);
GENERATED ALWAYS AS TRANSACTION START ID;
ALTER TABLE policy_info
ADD PERIOD SYSTEM_TIME(sys_start, sys_end);
To create a history table for this system-period temporal table, issue the following CREATE TABLE statement:
CREATE TABLE hist_policy_info
(policy_id CHAR(10) NOT NULL,
coverage INT NOT NULL,
sys_start TIMESTAMP(12) NOT NULL,
sys_end TIMESTAMP(12) NOT NULL,
trans_id TIMESTAMP(12));To define system-period data versioning between the system-period temporal table and the history table, issue the following ALTER TABLE statement:
ALTER TABLE policy_info
ADD VERSIONING USE HISTORY TABLE hist_policy_info;
A transaction-start-ID column that is defined as TIMESTAMP(12) with the GENERATED ALWAYS AS TRANSACTION START ID attribute. Defining this column as NOT NULL is optional.