標籤: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 主鍵自增長