復制代碼 代碼如下:
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;
由此可見,一旦把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;
由此可見,一旦把id設為identity類型,MS SQLServer數據庫會自動按遞增的方式為主鍵賦值。identity包含兩個參數,第一個參數表示起始值,第二個參數表示增量。
PS:2013-6-4
以前經常會碰到這樣的問題,當我們刪除了一條自增長列為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_INSERT
SET IDENTITY_INSERT customers OFF;
復制代碼 代碼如下:
create sequence customer_id_seq increment by 2 start with 1
復制代碼 代碼如下:
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;
通過觸發器自動添加id字段
從上述插入語句可以發現,如果每次都要插入customer_id_seq.nextval的值會非常累贅與麻煩,因此可以考慮使用觸發器來完成這一步工作。
創建觸發器trg_customers
復制代碼 代碼如下:
create or replace
trigger 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'); 

| 
 
 | 
新聞熱點
疑難解答