Oracle数据库主键值生成的两种解决方案
程序员文章站
2022-06-02 16:43:21
...
解决方案一:使用序列和触发器实现(推荐)
1、创建数据库表 设置主键
create table Test_Table(
id number(10) primary key, /*主键,自动增加*/
remake varchar2(20)
);
2、创建自动增长序列
CREATE SEQUENCE TestTable_Sequence
INCREMENT BY 1 -- 每次加几个
START WITH 1 -- 从1开始计数
NOMAXVALUE -- 不设置最大值
NOCYCLE -- 一直累加,不循环
CACHE 10;
3、创建触发器
CREATE TRIGGER Test_Increase BEFORE
insert ON Test_Table FOR EACH ROW
begin
select TestTable_Sequence.nextval into:New.id from dual;
end;
解决方案二:使用主键表存储表最大主键值
1、创建测试表和最大值存储表
create table Test_Table(
id number(10) primary key, /*主键,自动增加*/
remake varchar2(20)
);
create table SYS_MAXKEY(
id NUMBER not null, /*主键*/
tablename VARCHAR2(50), /*表名*/
keyname VARCHAR2(50),/*表主键字段名*/
maxkey NUMBER /*表主键当前最大值*/
);
2、为主键最大值记录表创建序列
create sequence SEQ_SYS_MAXKEY
minvalue 1
maxvalue 999999999999999999999999999
start with 0
increment by 1
cache 20;
3、创建存储过程
CREATE OR REPLACE PROCEDURE GETPK(
ATABLENAME VARCHAR,
AFIELDNAME VARCHAR,
APKVALUE OUT NUMBER) IS
COUNTNUM NUMBER;
MKEY NUMBER;
TTABLENAME VARCHAR(50);
TFIELDNAME VARCHAR(50);
DYNSTR VARCHAR(500);
MAXKEYID NUMBER;
BEGIN
TTABLENAME := UPPER(ATABLENAME);
TFIELDNAME := UPPER(AFIELDNAME);
SELECT COUNT(*)
INTO COUNTNUM
FROM SYS_MAXKEY
WHERE UPPER(TABLENAME) = TTABLENAME
AND UPPER(KEYNAME) = TFIELDNAME;
IF (COUNTNUM > 0) THEN
UPDATE SYS_MAXKEY
SET MAXKEY = MAXKEY + 1
WHERE UPPER(TABLENAME) = TTABLENAME
AND UPPER(KEYNAME) = TFIELDNAME returning MAXKEY into APKVALUE;
ELSE
--取对应表中的最大的主键 值
DYNSTR := 'begin
select max(' || TFIELDNAME || ') into :i_max from ' ||
TTABLENAME || ';
end ;';
EXECUTE IMMEDIATE DYNSTR
USING OUT APKVALUE;
IF APKVALUE IS NULL THEN
APKVALUE := 1;
ELSE
APKVALUE := APKVALUE + 1;
END IF;
--从序列中获取要写入sys_maxkey表的主键信息
SELECT SEQ_SYS_MAXKEY.NEXTVAL INTO MAXKEYID FROM DUAL;
--对取到的结果进行回写到sys_maxkey表中
INSERT INTO SYS_MAXKEY
(ID, TABLENAME, KEYNAME, MAXKEY, )
VALUES
(MAXKEYID, TTABLENAME, TFIELDNAME, APKVALUE,);
END IF;
COMMIT;
END;