2008年12月28日 星期日

Few notes of using identity column and identity_val_local function - DB2


/*
  Note: 最好還是不要使用 Identity column,免得找自己麻煩
  1) Create Table with identity column
  2) Return column value via identity_val_local function
  3) Different between insert statements
  4) Data movement
  5) Reset identity value
*/

/* 1) Create Table */

CREATE TABLE IDENTITY_LOG
(
 SEQID INTEGER NOT NULL
     GENERATED ALWAYS AS IDENTITY
     (START WITH 1 INCREMENT BY 1, NO CACHE),
 SYSDT TIMESTAMP
) IN USERSPACE1;

/* Insert data */

C:\>db2 insert into identity_log(sysdt) values (current timestamp)
DB20000I SQL 指令已順利完成。

/* 自動產生 seqid */

C:\>db2 select * from identity_log

SEQID    SYSDT
----------- --------------------------
      1 2008-12-29-10.52.54.665000

  已選取 1 個記錄。

/* 2) 使用Function Identity_val_local()取值 */

C:\>db2 values identity_val_local()

1
---------------------------------
                  1.

  已選取 1 個記錄。

/* Function Identity_val_local()只能在同一個connect下取值 */

C:\>db2 connect to sample

  資料庫連線資訊

 資料庫伺服器     = DB2/NT 9.5.0
 SQL 授權 ID     = ORION
 本地資料庫別名    = SAMPLE

C:\>db2 values identity_val_local()

1
---------------------------------
                  -

  已選取 1 個記錄。

/* 3) insert values 才能搭配 identity_val_local() */

C:\>db2 insert into identity_log(sysdt) select current timestamp from sysibm.sys
dummy1
DB20000I SQL 指令已順利完成。


/* 使用 insert select 時identity_val_local()取不到任何值,只保留最後一次產生的值 */

C:\>db2 values identity_val_local()

1
---------------------------------
                  1.

  已選取 1 個記錄。

/* 4) 使用Load時的方法 */

C:\>db2 select * from identity_log

SEQID    SYSDT
----------- --------------------------
      4 2008-12-29-11.01.18.560000
      5 2008-12-29-11.01.27.603000

  已選取 2 個記錄。

C:\>db2 export to identity_log.del of del select * from identity_log
SQL3104N 「匯出」公用程式正在開始將資料匯出至檔案 "identity_log.del"。

SQL3105N 「匯出」公用程式已完成,共匯出 "2" 列。

已匯出的列數:2

/* 清空 Table */

C:\>db2 alter table identity_log activate not logged initially with empty table
DB20000I SQL 指令已順利完成。

/* Modified by identityoverride */

C:\>db2 load from identity_log.del of del modified by identityoverride insert in
to identity_log

C:\>db2 select * from identity_log

SEQID    SYSDT
----------- --------------------------
      4 2008-12-29-11.01.18.560000
      5 2008-12-29-11.01.27.603000

  已選取 2 個記錄。

/* 5) Reset Identity 再由1開始 */

C:\>db2 alter table identity_log alter column seqid restart with 1
DB20000I SQL 指令已順利完成。

C:\>db2 insert into identity_log(sysdt) values (current timestamp)
DB20000I SQL 指令已順利完成。

C:\>db2 select * from identity_log

SEQID    SYSDT
----------- --------------------------
      1 2008-12-29-11.04.35.062000
      4 2008-12-29-11.01.18.560000
      5 2008-12-29-11.01.27.603000

  已選取 1 個記錄。