SQL獲取表中最新插入的記錄

2021-09-05 21:00:46 字數 2451 閱讀 2835

/*

對於想要得到乙個表中的最後乙個插入操作所產生的id的最好用ident_current('tbname')

*/insert

into

table

(field1,field2,

values

("field1value","field2value",

select

ident_current(

'recordid') 

asnewidvalue

/*對於馬上使用的剛才插入的新記錄id用scope_identity()是最合適的

*/insert

into

table

(field1,field2,

values

("field1value","field2value",

select

scope_identity

() as

newidvalue

/*對於想要得到一系列的操作中最後得到的那個自增的id最好用@@identity

*/insert

into

table

(field1,field2,

values

("field1value","field2value",

select

@@identity

asnewidvalue

《scope_identity和@@identity的區別》

scope_identity、ident_current 和 @@identity 是相似的函式,因為它們都返回插入到標識列中的值。

ident_current 不受作用域和會話的限制,而受限於指定的表。ident_current 返回為任何會話和作用域中的特定表所生成的值。呼叫它時必須提供表示表名的字元型引數,你可以得到你想要的任何表的最後乙個identity值,即使你的**裡沒有插入動作。例如:ident_current('t1');

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

例如,有兩個表 t1 和 t2,並且在 t1 上定義了 insert 觸發器。當將某行插入 t1 時,觸發器被激發,並在 t2 中插入一行。 該方案演示了兩個作用域:在 t1 上的插入,以及在 t2 通過觸發器的插入。

假設 t1 和 t2 都有標識列,@@identity 和 scope_identity 將在 t1 上的 insert 語句的最後返回不同的值。@@identity 將返回在當前會話中的任何作用域內插入的最後乙個標識列的值。這是在 t2 中插入的值。scope_identity() 將返回在 t1 中插入的 identity 值。這是在同乙個作用域內發生的最後的插入。如果在任何 insert 語句作用於作用域中的標識列之前呼叫 scope_identity() 函式,則該函式將返回空值。

scope_identy() 當前會話,當前作用域

@@identity  當前會話,所有作用域

---------------程式如下-----------------------

create table tz (

z_id  int identity(1,1)primary key,

z_name varchar(20) not null)

insert tz

values ('lisa')

insert tz

values ('mike')

insert tz

values ('carla')

select * from tz

gocreate table ty (

y_id  int identity(100,5)primary key,

y_name varchar(20) null)

insert ty (y_name)

values ('boathouse')

insert ty (y_name)

values ('rocks')

insert ty (y_name)

values ('elevator')

select * from ty

gocreate trigger ztrig

on tz

after insert as

begin

insert ty values ('')

endgo

insert tz values ('rosalie')

select scope_identity() as [scope_identity] 作用域:tz表

select   @@identity as [@@identity]  作用域:ty表

------------結果--------------

4

SQL 分組後獲取時間為最新的記錄

1.建立一張test表,表結構如下 create table test id int 11 not null name varchar 255 not null type varchar 255 not null create time timestamp primary key id 2.插入幾條...

mysql取出每個分組中最新的記錄

mysql取出每個分組中最新的記錄 mysql的gruop by分組功能沒有排序功能,所以我們如果想取出某個分組下的最新記錄是不太容易的,下面介紹兩種方法,一種是通過子查詢,一種是通過group concat函式來實現。一 表結構及資料插入 表的結構 test3 create table if no...

查詢組資料中最新記錄的集合

例項 現有一張統計表,是以task id和start time作為聯合主鍵的,每乙個任務可以啟動多次,這樣一來同乙個task id就會對應多個start time即多條統計記錄,現在要求將所有的任務統計出來,也就是查詢出task id唯一的集合,每條任務對應的是最新的一條統計記錄 1 select ...