MySql
在mysql中,如果把表的主鍵設為auto_increment類型,資料庫就會自動為主鍵賦值。例如:
create table customers(id int auto_increment primary key not null, name varchar(15));insert into customers(name) values("name1"),("name2");select id from customers;
以上sql語句先建立了customers表,然後插入兩條記錄,在插入時僅僅設定了name欄位的值。最後查詢表中id欄位,查詢結果為:
由此可見,一旦把id設為auto_increment類型,mysql資料庫會自動按遞增的方式為主鍵賦值。 Sql Server
在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');select id from customers;
注意:在sqlserver中字串用單引號擴起來,而在mysql中可以使用雙引號。
查詢結果和mysql的一樣。
由此可見,一旦把id設為identity類型,MS SQLServer資料庫會自動按遞增的方式為主鍵賦值。identity包含兩個參數,第一個參數表示起始值,第二個參數表示增量。 PS:2012-7-13
以前經常會碰到這樣的問題,當我們刪除了一條自增長列為1的記錄以後,再次插入的記錄自增長列是2了。我們想在插入一條自增長列為1的記錄是做不到的。今天跟同事討論的時候發現可以通過設定SET IDENTITY_INSERT <table_name> ON;來取消自增長,等我們插入完資料以後在關閉這個功能。實驗如下:
use TESTDB2--step1:建立表create table customers( id int identity primary key not null, name varchar(15));--step2:執行插入操作insert into customers(id,name) values(1,'name1');--報錯:An explicit value for the identity column in table 'customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.--step3:放開主鍵列的自增長SET IDENTITY_INSERT customers ON;--step4:插入兩條記錄,主鍵分別為1和3。插入成功insert into customers(id,name) values(1,'name1');insert into customers(id,name) values(3,'name1');--step5:再次插入一個主鍵為2的記錄。插入成功insert into customers(id,name) values(2,'name1');--step6:插入重複主鍵,--報錯:Violation of PRIMARY KEY constraint 'PK__customer__3213E83F00551192'. Cannot insert duplicate key in object 'dbo.customers'.insert into customers(id,name) values(3,'name1');--step7:關閉IDENTITY_INSERTSET IDENTITY_INSERT customers OFF;
2、從序列中擷取自動成長的標識符 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:先增加序列的值,然後返回序列值
以下sql語句先建立了customers表,然後插入兩條記錄,在插入時設定了id和name欄位的值,其中id欄位的值來自於customer_id_seq序列。最後查詢customers表中的id欄位。
create table customers(id int primary key not null, name varchar(15));insert into customers values(customer_id_seq.nextval, 'name1');insert into customers values(customer_id_seq.nextval, 'name2');select id from customers;
如果在oracle中執行以上語句,查詢結果為:
通過觸發器自動添加id欄位
從上述插入語句可以發現,如果每次都要插入customer_id_seq.nextval的值會非常累贅與麻煩,因此可以考慮使用觸發器來完成這一步工作。
建立觸發器trg_customers
create or replacetrigger trg_customers before insert on customers for each row begin select CUSTOMER_ID_SEQ.nextval into :new.id from dual; end;
插入一條記錄
insert into customers(name) values('test');
這是我們會發現這一條記錄被插入到資料庫中,並且id還是自增長的。