1. 自增字段IDENTITY
值由DB2生成,客户不能直接赋值
值可由DB2生成,也可以准许客户直接赋值,不过DB2不能保证提供的值唯一。
C. identity_val_local() 获取当前值
如insert into t1 (id,…) values (default,…)
Select identity_val_local() from sysibm.sysdummy1
insert into parent_table (pk_id,…) values (default,…)
insert into children_table (…,fk_id,…) values (,identity_val_local(),…)
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’); //insert 100 a1
Insert into t1(description) values (’a1’); //insert 101 a1
Insert into t1 values (200,’a1’); //erro
Commit;
Insert into t1(description) values (’a1’); //insert 102 a1
Rollback;
Insert into t1(description) values (’a1’); //insert 103 a1
Commit;
Select * from t1
100 a1
101 a1
103 a1
(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’); //insert 100 a1
Insert into t1(description) values (’a1’); //insert 101 a1
Insert into t1 values (200,’a1’); // insert 200 a1
Insert into t1 values (102,’a1’); // insert 102 a1
Commit;
Insert into t1(description) values (’a1’); //erro ,因此自增的当前值为102,数据库中已
经存在102的主键值了
Insert into t1(description) values (’a1’); //insert 103 a1
Commit;
Select * from t1
100 a1
101 a1
102 a1
103 a1
200 a1
2. Sequence
A.创建方式
Create sequence myseq
Start with 1
Increment by 1
No cycle
B.syntax(语法)
Nextval for
Prevval for
Example:
Insert into t1 (nextval for myseq ,…)
Select prevval for myseq from sysibm.sysdummy1
C.更改序列
ALTER SEQUENCE 序列名
可以修改的参数
START WITH的START_NUMBER
INCREMENT的VALUE1
NO MAXVALUE的数值
NO CYCLE属性
MAXIMUM NUMBER OF SEQUENCE VALUES最大数值
D.删除序列
DROP SEQUENCE 序列名
3. Index
语法:Create index index_name on 表名(col_name)
Example:
Create unique index index1 on t1(description) desc //创建唯一索引
Create index index1 on t1(description)allow reverse scans //准许反向检索
Create index index1 on t1(description)cluster allow reverse scans //簇索引
Create unique index index1 on t1(description)include (id)
//包含的列代表把值放到索引里面,这样通过索引查到要找的列时,直接可以找到列的值,不用再通过索引定位到数据页查找列值了,只有唯一索引才能有包含列
4. Foreign key
create table t1(id int not null primary key,description char(10)) in userspace1
create table t2(id int not null primary key,description char(10)) in userspace1
alter table t2 add constraint fk1 foreign key (id) referenceS t1(id) t1的id可以省略
约束的增加方式是按通用的方式:
ALTER TABLE 表名 add constraint 约束名 约束类型 列名,如: //增加约束
ALTER TABLE 表名 drop constraint约束名
比如alter table t1 add constraint pk1 primary key (id)
5. Check约束(和通用方式没有差别,具体见数据库开发人员版)
ALTER TABLE authors
ADD constraint authors_chk_phone check
(authors in (‘a’,’b’,’c’))
TRIGGER不能修改,只能删除重建
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9524210/viewspace-462715/ ,如需转载,请注明出处,否则将追究法律责任。