I would like to have a stored procedure which inserts rows into a table (retrieved from a select query from another table) and for each newly inserted row gets its identity and updates the original table with the identity
Pseudo code-
records = select id,city,state,country from USER where name=@name
for each record in records // for each rows selected
insert into LOCATION(city,state,country) values(@record.city,@record.state,@record.country); //inserts a value into LOCATION table
@id = SCOPE_IDENTITY(); // gets the identity of the newly inserted row
update USER set LocationId=@id where Id=@record.id //updates the new id back to old table's column
end
This is a data migration task, where we want to segregate the LOCATION from USER table
Thanks in advance for your time and effort for this thread.
You could do something like this:
With this, you now have the inserted values – including the newly defined identity values – in your
@InsertedValuestable variable and you can now update the source table as you see fit.This doesn’t require any cursor or any other messy RBAR (row-by-agonizing-row) processing at all – everything is nicely set-based and as fast as it can possibly be.
Learn more about the
OUTPUTclause at MSDN SQL Server Books Online – you can use theOUTPUTclause on insert, update and even delete statements, too!