MySQL 和 Oracle 主鍵自增長

來源:互聯網
上載者:User

標籤:nextval   constrain   height   計數   body   operator   begin   ace   mail   

1、MySQL

1)建表

 auto_increment:每插入一條資料,客戶表(customers)的主鍵id就自動增1,如下所示

 1 create table customers    -- 建立客戶表 2 ( 3     id int auto_increment primary key not null,  -- auto_increment:自增長 4     name varchar(15) 5 ); 6 

 

2)測試(執行個體)

1 insert into customers(name) values("張三"),("李四");-- 向客戶表中插入資料2 3 select * from customers; -- 查詢客戶表

 

 

 

2、Oracle

1)建表

 1 create table student 2 ( 3   id       number not null,  -- 主鍵 4   name     varchar2(20), 5   birthday  date, 
6 age     number(20),
7 phone varchar2(60),
8 email varchar2(10)
9 )
10 alter table student add constraint student_pk primary key (id); -- 主鍵

 

2)建立序列

 1 /* 2 --建立序列Sequence 3 create sequence student_id 4 minvalue 1  --最小值 5 nomaxvalue  --不設定最大值(由機器決定),或 根據表欄位的值範圍設定 maxvalue
6 maxvalue 99999999 -- 最大值 7 start with 1 --從1開始計數,數值可變 8 increment by 1 --每次加1,數值可變 9 nocycle --一直累加,不迴圈10 nocache --不建緩衝區,如果建立cache那麼系統將自動讀取cache值個seq,這樣會加快運行速度;如果當機或oracle死了,那麼下次讀取的seq值將不連貫11 */12
1314 -- 建立序列 15 create sequence student_id16 increment by 1 17 start with 1;

 

3)建立觸發器

格式:

  create or replace trigger 觸發器名  before insert on 表名 for each row when (new.表的自增長欄位 is null)  begin    select 序列名.Nextval into:new.表的自增長欄位 from dual;  end;
1 -- 建立觸發器 2 create or replace trigger tg_insertId3 before insert on student for each row when (new.id is null)4 begin5   select student_id.Nextval into:new.id from dual;6 end;

 

4)測試(執行個體)

1 INSERT INTO student(name,birthday,age,phone,email) 2     VALUES(‘zhangsan‘,to_date(‘2018-01-10 19:55:45‘,‘yyyy-MM-dd hh24:mi:ss‘),18,‘13510086110‘,‘[email protected]‘);  -- 插入資料
3
4 INSERT INTO student(name,birthday,age,phone,email) 5 VALUES(‘zhangsan‘,to_date(‘2018-01-11 19:55:45‘,‘yyyy-MM-dd hh24:mi:ss‘),20,‘13510086110‘,‘[email protected]‘);
6
78 select * from student; -- 查詢學生表

 

 

 

DSHORE

出處:http://www.cnblogs.com/dshore123/

歡迎轉載,轉載務必說明出處。(如果本文對你有用,可以點擊一下右下角的 推薦,謝謝!

 

MySQL 和 Oracle 主鍵自增長

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.