0

I'm inserting several rows into a table A which has an instead of insert trigger and an identity column.

Then I need to insert so many rows in a table B where each row hold a reference to the rows inserted in A.

The problem is, I can't use the output clause on A since, the identity will not be set (due to the trigger).

I know for one row I could use @@identity as long as the insertion of rows in A is the last insertion statement inside the trigger, but here I'm talking about multiple rows.

How can I achieve this?

4
  • 1
    Friend had a similar problem, I blogged about it here. Feb 7, 2014 at 14:19
  • are you inserting in table A and table B in same proc ?i think you hv to use one temp table
    – KumarHarsh
    Feb 7, 2014 at 14:25
  • I would suggest to create those Identities appropriately before hand and use those to insert in to the tableA and TableB.
    – Anup Shah
    Feb 7, 2014 at 14:57
  • this is very good question .It can be dome without temp table i)Create View on table A and table B ii)Create instead of trigger on view. iii)here after insert into view passing all the value iv)inside trigger write query to insert in TableA using output v)Next statement inside trigger insert into TableB Try and let us know.
    – KumarHarsh
    Feb 7, 2014 at 15:15

1 Answer 1

0

I used code like this ( You CAN use table variable in OUTPUT clause )

declare @T table (requestID int); 
INSERT <tableA> (<fields>) 
       OUTPUT inserted.RequestID into @T 
VALUES( <fieldValues1> ),( <fieldValues2> ) ; 
Insert <tableB> (ID) select RequestID from @T;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.