Skip to content
Advertisement

How do I insert multiple rows with many to many relations into ‘Table1’ from ‘Table1’?

I’m trying to copy an existing ship, with all of its contents of its child tables (for lack of a better term) and their relations. So far I’ve got most of the copying down except for the ship’s tables that have a many to many relation. An example of my current situation is as follows:

I have two individual tables and a third table that connects them both:

Facilities

Deck

FacilitiesToDeck

As you can see above, it is possible for FacilitiesToDeck to have multiple rows with the same DeckId as there can be multiple facilities on the same deck level. Same goes for FacilitiesId as there can be facilities that spand over multiple deck levels.

Now, when I copy a ship with its child entities I expect the above tables to look like this:

Facilities

Deck

FacilitiesToDeck

My stored procedure is meant to insert multiple new rows of data from FacilitiesToDeck into FacilitiesToDeck, but where the ShipId, FacilitiesId and DeckId are the new ID values that I create earlier in my stored procedure for Facilities and Deck. However, I fail to see (or find on the internet) a solution on how to do this as every value of every new row that’s being inserted into FacilitiesToDeck is different, with seemingly no correlation (at least to me and my peers).

The following is a snippet of my current stored procedure:

And this the result of my current code:

FacilitiesToDeck

As you can hopefully tell above, my current procedure ends up inserting all new facilities on every new deck, instead of inserting the new facilities with their intended deck. This output makes sense now when I review my code but I still can’t come up with a solution of doing what I intend to do. I want the newly inserted rows FacilitiesToDeck to have the new IDs from Facilities and Deck.

Anyone got an idea?

EDIT: Added my own attempt and its resulting output.

Advertisement

Answer

Here is an example:

I don’t claim that it is the best performing or the nicest solution, but this would work if your xxxId columns are identity columns. I haven’t added any error checking; ideally you should have a try-catch block and rollback all inserts, if anything fails. identity inserts are there to simulate your sample data, while having identity columns.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement