Question

I have a small process that works on a few SQL tables. The tables were originally Guid primary keyed, but for efficiency we're updating them to a BigInt identity.

I have a batch insert that adds an item in the primary key table, then several items in the foreign key table. With Guids, this was easy, as I'd create the Guid in the code and pass it in for the parameter.

I'm curious what the best approach is for an identity column? I know I can do :

declare @id int 
insert into PrimaryKeyTable (...) Values (...)
select @id = Scope_Identity()

and get back the primary key.

Is the best approach to split the batches into two, and pass the parameter back in in the code for the foreign key inserts? Or is there a way to do all the inserts in one SQL statement? Is there a general public opinion on the matter, or a best-practice? Thankyou for any guidance.

Was it helpful?

Solution

You need to use OUTPUT

INSERT...
OUTPUT INSERTED.ID

This allows you to do a batch insert and it will spit out the batched identity ID's and whatever else you explicitly set to output

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top