I have to perform a bulk operation bool AddEntitiesX(List<X>):
- For each insert of
XintoX_Table(withX_UIDas auto-increment ID), I have to insert k-times another entityYintoY_Table(withX_UIDas FK andY_UIDas auto-increment ID), sinceXcontains a list of k–Yentities. - Then, for each inserted
X, I need to insert also aZentity inZ_Table(withX_UIDas FK andZ_UIDas auto-increment ID).
My pseudo-code will look like this:
// cannot use 'TransactionScope' since there are problems with Oracle
// so, prepare SqlTransaction
foreach (X)
{
//1. call 'InsertX' SP
foreach (Y in x.ListY)
//2. call 'InsertY' SP
//3. call 'InsertZ' SP
}
// commit transaction
How can I retrieve the X_UID from InsertX SP to pass to the next stored procs?
If there is no way, then since I cannot have this big transaction in one stored procedure, how should I model it?
I would like to know best practices to handle this kind of operations from business to data layer using transactions.
Thank you… and please let me know if my question is not clear enough.
One way is to use
SCOPE_IDENTITY(), like cdel already suggested. Another way is to use the OUTPUT clause of INSERTThis inserts the record and also produces a result set, which contains the inserted row generated identity value. In C# you read this result set just as if you’d have executed a SELECT, ie. you use
ExecuteReader().One advantage of using OUTPUT clause is that is the only way it can reliable return multiple row IDs. Say you insert not one, but 100, you can get back the IDs of all 100 inserted rows in a single result set. In case you wonder how to insert 100 rows in one swoop, see Arrays and Lists in SQL Server 2008: Using Table-Valued Parameters.
Another advantage of using OUTPUT clause is that you can chain two statements into a single one, see Chained Updates.