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 2 start with 1

 

一旦定義了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 procedure p_create_table 
Authid Current_User is
begin
Execute Immediate 'create table create_table(id int)';
end p_create_table;
 

 

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章