關於資料庫中的主鍵的自動成長__資料庫

來源:互聯網
上載者:User
              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_cr table  Authid Current_User is
begin
Execute Immediate 'create table create_table(id int)';
end p_create_table;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.