See Also
You are here: SQL Reference > SQL Functions and Operators > Scope Functions > SCOPE_IDENTITY
ContentsIndexHome
PreviousUpNext
SCOPE_IDENTITY
SCOPE_IDENTITY

 

Syntax

SCOPE_IDENTITY()

 

Returns the last identity value inserted into an incremental column in the same SQL batch scope. 

 

Example  

use test;

declare @id bigint;

--create table with 2 identity columns
create table product  (
id1 uniqueidentifier not null primary key,
id2 bigint not null default(AutoIdentity()),
name varchar);

--create table to store products transaction
create table [log]  (
id1 bigint,
id2 bigint,
[time] datetime default(getdate()));

go; --execute create tables

--insert into products, and to log with the identity value of the products row
Insert into product(name) values('myproduct');
set @id = scope_identity();
Insert into [log](id1,id2) values(@id,@id+1);
--return inserted rows
select * from [log]

 

Related