db2 获取自增主键的方法

时间:2022-06-01 21:18:04

1.用SEQUENCES方式

建表语句

CREATE TABLE TEST1(
 PKEY INTEGER NOT NULL,
 NAME VARCHAR(100),
 SEX VARCHAR(100),
 AGE INTEGER,
 IS_DELETE SMALLINT,
 CREATED_TIME TIMESTAMP,
 CONSTRAINT XASZ_ORDER_UNION_PK PRIMARY KEY (PKEY)
);

创建SEQUENCES

CREATE SEQUENCE SEQ_TEST1

START WITH 1  --此行中的2修改为自己想要修改的值
INCREMENT BY 1
MINVALUE 0
NOCACHE 
NOCYCLE 
NOORDER

插入、查询自增语句

insert into TEST1(TEST1.PKEY,TEST1.NAME,TEST1.AGE,TEST1.SEX,TEST1.IS_DELETE) VALUES(NEXT value FOR MXCGMS.SEQ_TEST1,'张三',18,'男',1 );

SELECT LAST_NUMBER as PKEY FROM USER_SEQUENCES WHERE SEQUENCE_NAME='SEQ_TEST1' 

2.用表内字段自增

建表语句

CREATE TABLE TEST2(
 PKEY INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY(START WITH 1 INCREMENT BY 1),
 NAME VARCHAR(100),
 SEX VARCHAR(100),
 AGE INTEGER,
 IS_DELETE SMALLINT,
 CREATED_TIME TIMESTAMP,
 CONSTRAINT XASZ_ORDER_UNION_PK PRIMARY KEY (PKEY)
);
GENERATED BY DEFAULT AS IDENTITY(START WITH 1 INCREMENT BY 1)这条语句作用是,将主键设置为自增。但是仅作用于此表

插入、查询自增语句
insert into TEST2(PKEY,NAME,AGE,SEX,IS_DELETE) VALUES(default,'张三',18,'男',1 );

SELECT IDENTITY_VAL_LOCAL() as PKEY FROM SYSIBM.SYSDUMMY1;