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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With