Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting new IDs after insert

I'm inserting a bunch of new rows into a table which is defined as follows:

CREATE TABLE [sometable](     [id] [int] IDENTITY(1,1) NOT NULL,     [someval] sometype NOT NULL ) 

using the following insert:

insert into sometable select somefield as someval from othertable 

when I've finished, I'd like to know the IDs of all the newly inserted rows. SCOPE_IDENTITY() only returns the ID last row inserted.

How can I get all the new IDs?

One method that springs to mind would be to grab the current largest identity from sometable and the scope_identity() post-insert, and use these two values to select from sometable. For example:

declare @currentMaxId int; select @currentMaxId=MAX(id) from sometable insert into sometable select somefield as someval from othertable select * from sometable where id>@currentMaxId and id<=SCOPE_IDENTITY() 

Is there a better pattern?

like image 435
spender Avatar asked May 01 '09 10:05

spender


People also ask

How do I get my ID back after insert?

The @@Identity function will return the last identity value inserted in the current session, in any table and in any scope. The Scope_Identity() function will return the last identity value inserted in the current scope (and session), in any table.

How do you get ID of the newly inserted record in a database?

IDENT_CURRENT() will give you the last identity value inserted into a specific table from any scope, by any user. @@IDENTITY gives you the last identity value generated by the most recent INSERT statement for the current connection, regardless of table or scope.

How do I get the latest inserted record ID in SQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

What does insert into return?

An SQL INSERT statement writes new rows of data into a table. If the INSERT activity is successful, it returns the number of rows inserted into the table.


1 Answers

Use the OUTPUT functionality to grab all the INSERTED Id back into a table.

CREATE TABLE MyTable (     MyPK INT IDENTITY(1,1) NOT NULL,     MyColumn NVARCHAR(1000) )  DECLARE @myNewPKTable TABLE (myNewPK INT)  INSERT INTO      MyTable (     MyColumn ) OUTPUT INSERTED.MyPK INTO @myNewPKTable SELECT     sysobjects.name FROM     sysobjects  SELECT * FROM @myNewPKTable 
like image 80
Robin Day Avatar answered Oct 23 '22 11:10

Robin Day