Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi,I would appreciate some advice for the best approach with the following scenario:I would like a single sproc to receive parameters from a page that supplies insert data for table1 and looping (for each) information for table2. table2 is the junction box for multiple choices linked through standard many to many relationship.The expectation is that I insert the data into table1 which creates the new identity to be used in conjunction with the multiple choice values. Using @@identity I hoped to have a second insert statement that would take in the looping choices and insert into the junction table.I have checked that the loop works as expected. I have managed to grab the @@identity but I am in a situation where the initial insert is being run as many times as the options for the junction table2.Please advise if I am trying the wrong method and if there is a best practice that I should follow.Thank you in advanceJay
RickD
Slow But Sure Yak Herding Master
3608 Posts
Posted - 2010-11-04 : 07:20:16
Why not use OUTPUT instead?
DECLARE @Table TABLE (identityfield INT)INSERT INTO Table1SELECTField1,Field2,Field3OUTPUT identityfield into @tableFROMTable (Or derived table)
Then:
INSERT INTO TABLE2SELECTidentityfieldfield1,field2FROM@Table
There is no need to loop as you can then write the second query to insert all rows required without a loop.Try to think in a set based way rather than a procedural way..