Oracle数据库中,通过function的方式建立自增字段

Oracle数据库无自增字段设置,可以通过function的方式设置字段自增来作为ID。

1、创建表tSequence来存储各表的next ID。

2、创建function类似如下:

 1 CREATE OR REPLACE FUNCTION "FUNC_NEXTID"
 2 (tablename in varchar2) return number is
 3 
 4   nextid number(12);
 5 begin
 6   begin
 7     select nvl(max(id),-1) into nextid from tSequence where upper(name) = upper(tablename);
 8   exception
 9     when no_data_found then nextid := 0;
10   end;
11 
12   if nextid = -1 then
13     INSERT INTO tSequence(name,id) VALUES(tablename,1);
14     nextid := 1;
15   else
16     update tSequence set id = id+1 where upper(name) = upper(tablename);
17     select nvl(max(id),-1) into nextid from tSequence where upper(name) = upper(tablename);
18   end if;
19 
20   return(nextid);
21 end FUNC_NEXTID;

3、调用方法

insert into tablename ( ID, 列1,,列2) values (func_nextid('tablename'), '列1值', '列2值' )

原文地址:https://www.cnblogs.com/moleme/p/4917798.html