首页 > 学院 > 开发设计 > 正文

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

2019-11-08 20:54: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)asstrsql varchar2(1000);beginstrsql := '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 isbeginExecute Immediate 'create table create_table(id int)';end p_create_table;
上一篇:Mysql中文乱码

下一篇:Sql注入漏洞问题

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表