Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SCOPE_IDENTITY to retrieve the last ID that was inserted

Suppose I have two table. First table's primary key is the foreign key for another table.

Table Member has its primary key as the foreign key in Member_detail.

So when I insert a row in Member table using a Stored Procedure, I need to get the primary key value to add to the Member_detail table.

One way I was using is :

SELECT Max(MemberID) 
FROM Member

Then passing this Memberid to my Member_detail table, but on the following post, I read that the Max function is not recommended and that I should use SCOPE_IDENTITY, but I don't know how to use of it.

Can anyone give me some example?

like image 902
NightKnight Avatar asked Jan 24 '12 11:01

NightKnight


2 Answers

I've seen "funny" behavior with scope_identity. As a result, I like to use an output clause. Here's an example:

declare @id table (i int)
insert into Member (name) values ('NightKnight')
output (MemberId) into @id

select * from @id
like image 149
Ben Thul Avatar answered Nov 06 '22 15:11

Ben Thul


SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope.

Given you have 2 tables:

Member: id int (primaryKey), name varchar

Member_Detail: id int (primaryKey), pk int (foreignKey), name varchar

You can do this:

DECLARE @MemberId int

INSERT INTO Member (name) VALUES ('hello');

SET @MemberId = SCOPE_IDENTITY()

INSERT INTO Member_Detail (pk, name) VALUES (@MemberId, 'hello again')

MSDN Reference:

SCOPE_IDENTITY (Transact-SQL)

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

like image 26
stian.net Avatar answered Nov 06 '22 16:11

stian.net