标签:
1、把主键定义为自动增长标识符类型
在mysql中,如果把表的主键设为auto_increment类型,数据库就会自动为主键赋值。例如:
create table customers(id int auto_increment primary key not null, name varchar(15));
insert into customers(name) values("name1"),("name2");
select id from customers;
以上sql语句先创建了customers表,然后插入两条记录,在插入时仅仅设定了name字段的值。最后查询表中id字段,查询结果为:
id
1
2
由此可见,一旦把id设为auto_increment类型,mysql数据库会自动按递增的方式为主键赋值。
在MS SQLServer中,如果把表的主键设为identity类型,数据库就会自动为主键赋值。例如:
create table customers(id int identity(1,1) primary key not null, name varchar(15));
insert into customers(name) values("name1"),("name2");
select id from customers;
查询结果和mysql的一样。由此可见,一旦把id设为identity类型,MS SQLServer数据库会自动按递增的方式为主键赋值。identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。
在DB2中,如果把表的主键设置为:
UserID integer not null generated always as identity (start with 1,increment by 1),
2、从序列中获取自动增长的标识符
1、序列定义
ORACLE:
CREATE SEQUENCE <sequence_name>
INCREMENT BY <integer>
START WITH <integer>
MAXVALUE <integer> / NOMAXVALUE
MINVALUE <integer> / NOMINVALUE
CYCLE / NOCYCLE
CACHE <#> / NOCACHE
ORDER / NOORDER;
DB2:
CREATE SEQUENCE <sequence-name>
AS data-type 默认 As Integer
START WITH <numeric-constant>
INCREMENT BY <numeric-constant> 默认 INCREMENT BY 1
MINVALUE <numeric-constant> | NO MINVALUE 默认 NO MINVALUE
MAXVALUE <numeric-constant> | NO MAXVALUE 默认 NO MAXVALUE
NO CYCLE | CYCLE 默认 NO CYCLE
CACHE <numeric-constant> | NO CACHE 默认 CACHE 20
NO ORDER | ORDER 默认 NO ORDER
2、序列取值
取下一个值:
ORACLE: 序列.NEXTVAL
DB2: NEXTVAL FOR 序列 或 NEXT VALUE FOR 序列
取当前值:
ORACLE: 序列.CURRVAL
DB2: PREVIOUS VALUE FOR 序列 或 PREVVAL FOR 序列
3、序列设置开始值
ORACLE:取得下一个值;先设置步长(下一个值 与 设置的开始值之间差);取得下一个值;再把步长修改成原来值
DB2:ALTER SEQUENCE 序列名 RESTART WITH 下一值
4、修改
ORACLE:
修改最大值 ALTER SEQUENCE <sequence_name> MAX VALUE <integer>
修改最小值: ALTER SEQUENCE <sequence_name> MIN VALUE <integer> (此值需要比当前值小)
修改步长: ALTER SEQUENCE <sequence_name> INCREMENT BY <integer>;
修改CACHE值: ALTER SEQUENCE <sequence_name> CACHE <integer> | NOCACHE
修改循环属性: ALTER SEQUENCE <sequence_name> <CYCLE | NOCYCLE>
修改排序属性:ALTER SEQUENCE <sequence_name> <ORDER | NOORDER>
DB2:
修改最大值: ALTER SEQUENCE <sequence_name> MAX VALUE <numeric-constant> | NO MAXVALUE
修改最小值: ALTER SEQUENCE <sequence_name> MIN VALUE <numeric-constant> | NO MINVALUE (此值需要比当前值小)
修改步长: ALTER SEQUENCE <sequence_name> INCREMENT BY <numeric-constant>;
修改CACHE值: ALTER SEQUENCE <sequence_name> CACHE <numeric-constant> | NO CACHE
修改循环属性: ALTER SEQUENCE <sequence_name> <CYCLE | NO CYCLE>
修改排序属性:ALTER SEQUENCE <sequence_name> <ORDER | NO ORDER>
从新计数: ALTER SEQUENCE <sequence_name> RESTART | RESTART WITH <numeric-constant>
5、DROP
ORACLE: DROP SEQUENCE <sequence_name>;
DB2: DROP SEQUENCE <sequence_name>;
6、例句
CREATE SEQUENCE JOBSHOW_SEQ
AS INTEGER
CACHE 20
MAXVALUE 999999
ORDER;
CREATE SEQUENCE JOBWORK_SEQ
AS INTEGER
CACHE 20
MAXVALUE 999999
ORDER;
CREATE SEQUENCE YN_SEQ
AS INTEGER
MAXVALUE 99999999;
select yn_seq.nextval from YNZP_JOB_JOBINFO
select nextval for KFCMCC_SEQ from sysibm.sysdummy1
标签:
原文地址:http://www.cnblogs.com/zmc/p/4688941.html