关于数据库中的主键的自动增长

来源:互联网 发布:域中软件推送安装 编辑:程序博客网 时间:2024/04/29 18:31
              Mysql、SqlServer、Oracle主键自动增长的设置
      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");

       2、在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");
identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。

       3、Oracle列中获取自动增长的标识符
在Oracle中,可以为每张表的主键创建一个单独的序列,然后从这个序列中获取自动增加的标识符,把它赋值给主键。
例如一下语句创建了一个名为customer_id_seq的序列,这个序列的起始值为1,增量为2。

方法一、
    create sequence customer_id_seq
      INCREMENT BY 1   -- 每次加几个  
      START WITH 1     -- 从1开始计数  
      NOMAXVALUE       -- 不设置最大值  
      NOCYCLE          -- 一直累加,不循环  
      CACHE 10;
一旦定义了customer_id_seq序列,就可以访问序列的curval和nextval属性。
curval:返回序列的当前值
nextval:先增加序列的值,然后返回序列值
create table customers(id int primary key not null, name varchar(15));
insert into customers values(customer_id_seq.curval, "name1"),(customer_id_seq.nextval, "name2");

方法二、或者通过存储过程和触发器:
    1、通过添加存储过程生成序列及触发器:
create or replace PROCEDURE "PR_CREATEIDENTITYCOLUMN"
(tablename varchar2,columnname varchar2)
as
strsql varchar2(1000);
begin
strsql := 'create sequence seq_'||tablename||' minvalue 1 maxvalue 999999999999999999 start with 1 increment by 1 nocache';
execute immediate strsql;
strsql := 'create or replace trigger trg_'||tablename||' before insert on '||tablename||' for each row begin select seq_'||tablename||'.nextval into :new.'||columnname||' from dual; end;';
execute immediate strsql;
end;

2、 对表进行执行存储过程
exec PR_CREATEIDENTITYColumn('XS_AUDIT_RECORD','AUDIT_RECORD_ID');
   上一种方案对每一张表都要进行,下面根据用户批量生成
select a.table_name, b.column_name  from dba_constraints a, dba_cons_columns b 
where a.constraint_name = b.constraint_name 
and a.CONSTRAINT_TYPE = 'P' 
and a.owner=user;
 
3、添加执行存储过程的role权限,修改存储过程,加入Authid Current_User时存储过程可以使用role权限。
 create or replace procedeate_
ure p_crtable 
Authid Current_User is
begin
Execute Immediate 'create table create_table(id int)';
end p_create_table;

0 0