SQL語句 插入資料的同時,返回ID值 (自增)

2021-06-01 05:36:04 字數 2280 閱讀 9965

2000中,有三個比較類似的功能:他們分別是:scope_identity、ident_current 和 @@identity,它們都返回插入到 identity 列中的值。

ident_current 返回為任何會話和任何作用域中的特定表最後生成的標識值。ident_current 不受作用域和會話的限制,而受限於指定的表。ident_current 返回為任何會話和作用域中的特定表所生成的值。

@@identity 返回為當前會話的所有作用域中的任何表最後生成的標識值。

scope_identity 返回為當前會話和當前作用域中的任何表最後生成的標識值

scope_identity 和 @@identity 返回在當前會話中的任何表內所生成的最後乙個標識值。但是,scope_identity 只返回插入到當前作用域中的值;@@identity 不受限於特定的作用域。

例如,有兩個表 t1 和 t2,在 t1 上定義了乙個 insert 觸發器。當將某行插入 t1 時,觸發器被激發,並在 t2 中插入一行。此例說明了兩個作用域:乙個是在 t1 上的插入,另乙個是作為觸發器的結果在 t2 上的插入。

假設 t1 和 t2 都有 identity 列,@@identity 和 scope_identity 將在 t1 上的 insert 語句的最後返回不同的值。

@@identity 返回插入到當前會話中任何作用域內的最後乙個 identity 列值,該值是插入 t2 中的值。

scope_identity() 返回插入 t1 中的 identity 值,該值是發生在相同作用域中的最後乙個 insert。如果在作用域中發生插入語句到標識列之前喚醒呼叫 scope_identity() 函式,則該函式將返回 null 值。

而ident_current('t1') 和 ident_current('t2') 返回的值分別是這兩個表最後自增的值。

ajqc的實驗:(40條本地執行緒,40+40條遠端執行緒同時併發測試,插入1200w行),得出的結論是: 

1.在典型的級聯應用中.不能用@@identity,在cii850,256m sd的機器上1w多行時就會併發衝突.在p42.8c,512m ddr上,才6000多行時就併發衝突. 

2.scope_identity()是絕對可靠的,可以用在儲存過程中,連觸發器也不用建,沒併發衝突

select   ident_current('tablename')   --返回指定表中生成的最後乙個標示值   

select   ident_incr('tablename')--返回指定表的標示字段增量值

select   ident_seed('tablename')--返回指定表的標示字段種子值

返回最後插入記錄的自動編號

select ident_current('tablename')

返回下乙個自動編號:   

select   ident_current('tablename')   +   (select   ident_incr('tablename'))

select @@identity --返回當前會話所有表中生成的最後乙個標示值

插入資料的同時,返回id值

前幾天在做專案時,遇到插入資料的同時,返回id值的問題,遂記錄如下:

插入資料的同時,返回id值的sql語句。

mssql:

insert into test2 (aa)   values ('cc')   select @@identity as sequence

mysql:

select last_insert_id() as id from t_d_nm_shop_templet limit 1

在ibatis中,可以這樣配置:

insert into t_d_qt_task (`taskgroup_id` ,`task_name`

,`task_content` , `test_object` ,`priority`,`status`, `user_id`

,`script_type` ) values(?,?,?,?,'9',?,?,?)

select last_insert_id() as task_id from t_d_qt_task limit 1

select seq_d_qt_task.nextval as id from dual

insert into t_d_qt_task (task_id,taskgroup_id ,task_name

,task_content , test_object ,priority,status, user_id

,script_type ) values(?,?,?,?,?,'9',?,?,?)

sql語句插入一條記錄同時獲取剛插入的id

有兩種方式可以獲得剛新插入的id 從inserted臨時表中查詢 使用全域性變數 identity 查詢 1 使用 output 關鍵字輸出,inserted 為已插入的臨時表,這樣就可以得到剛剛插入該錶的 id 了。insert into t student name,studentno,age ...

MyBatis MySQL 返回插入的主鍵ID

需求 使用mybatis往mysql資料庫中插入一條記錄後,需要返回該條記錄的自增主鍵值。insert into basic organ buss parent id,buss name,buss alias,status,creater,create date,updater,update dat...

Mysql批量插入資料sql語句

假定我們的表結構如下 create table example example id int not null,name varchar 50 not null,value varchar 50 not null,other value varchar 50 not null 通常情況下單條插入的s...