DB2自增字段IDENTITY應該如何使用呢?相信這是很多人都提到過的問題,下面就為您詳細介紹DB2自增字段IDENTITY的用法,供您參考。
A.Generated always
值由DB2生成,客戶不能直接賦值
- Example:
- Create table t1
- (id int generated always as identity (start with 100 increment by 1),description char(10));
- Commit;
- Insert into t1 values (default,’a1’); //insert100 a1
- Insert into t1(description) values (’a1’); //insert101 a1
- Insert into t1 values (200,’a1’); //erro
- Commit;
- Insert into t1(description) values (’a1’); //insert102 a1
- Rollback;
- Insert into t1(description) values (’a1’); //insert103 a1
- Commit;
- Select * from t1;
- 100 a1
- 101 a1
- 103 a1
B.Generated by default
值可由DB2生成,也可以准許客戶直接賦值,不過DB2不能保證提供的值唯一。
- Example:
- Create table t1
- (id int generated by default as identity (start with 100 increment by 1),description char(10)) in userspace1
- Commit;
- Insert into t1 values (default,’a1’); //insert100 a1
- Insert into t1(description) values (’a1’); //insert101 a1
- Insert into t1 values (200,’a1’); // insert200 a1
- Insert into t1 values (102,’a1’); // insert102 a1
- Commit;
- Insert into t1(description) values (’a1’); //erro ,因此自增的當前值為102,數據庫中已經存在102的主鍵值了
- Insert into t1(description) values (’a1’); //insert103 a1
- Commit;
- Select * from t1;
- 100 a1
- 101 a1
- 102 a1
- 103 a1
- 200 a1
以上DB2自增字段IDENTITY的用法介紹。