Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ID of last inserted records [duplicate]

I'm inserting multiple records to a table using the below query:

INSERT INTO Table1(FirstName, LastName, EmailAddress)
    SELECT t2.FirstName, t2.LastName, t2.EmailAddress
    FROM Table2 t2

Since the query is inserting multiple records, I can't use SCOPE_IDENTITY to retrieve PK. Is there any method to get the ID's of last inserted records?

like image 372
NaveenBhat Avatar asked Mar 16 '11 09:03

NaveenBhat


1 Answers

SCOPE_IDENTITY() will correctly give you the LAST ID. What you need is to combine it with @@Rowcount to give you the range of IDs. As the other Richard points out, this only works if your increment is set to 1

For example:

declare @last int, @first int
insert ...
select @last = scope_identity(), @first = scope_identity() - @@rowcount + 1

Another way (use this in SQL Server 2008 for guaranteed results) to do this is to use the OUTPUT clause

declare @ids table (id int)
INSERT INTO Table1 (FirstName ,LastName ,EmailAddress)
output inserted.id into @ids

-- Get the ids
SELECT id from @Ids

The table now contains all the inserted ids

like image 150
RichardTheKiwi Avatar answered Nov 15 '22 11:11

RichardTheKiwi