Background: I have a Stored Procedure whose purpose is to "snapshot" the data from "live tables" into the "snapshot tables". I'm passing in table-valued-parameters for performance reasons. The data from the "live tables" are hierarchical in nature (grandparent-parent-child). The database schema is fixed, as of now. Actually it would be easy to fix this problem if I have the liberty to add one more column, but for now I am not allowed to.
Problem: Currently I am stuck at the ChildSnapshot table. I don't know how to get the value of the SnapshotParentId given the database schema. I am not allowed to add "OrigParentId" at the ParentSnapshot table. Please check my stored proc to see where I am stuck.
So these are the "live tables":
(I put A,B,C,X,Y,Z for id columns instead of numbers to easily demonstrate the relationship between tables)
Table: GrandParent
╔════╦══════╗
║ id ║ Data ║
╠════╬══════╣
║ A  ║ Kris ║
╚════╩══════╝
Table: Parent
╔════╦══════╦══════════╗
║ id ║ Data ║ GrannyId ║
╠════╬══════╬══════════╣
║ B  ║ Kim  ║ A        ║
╚════╩══════╩══════════╝
Table Child
╔════╦═══════╦══════════╗
║ id ║ Data  ║ ParentId ║
╠════╬═══════╬══════════╣
║ C  ║ North ║ B        ║
╚════╩═══════╩══════════╝
While these are the "live" tables, containing my expected results as well:
Table GrandParentSnapshot:  
╔════╦═══════╦══════════╗
║ id ║ Data  ║ OrigId   ║
╠════╬═══════╬══════════╣
║ X  ║ Kris  ║ A        ║
╚════╩═══════╩══════════╝
Table ParentSnapshot:  
╔════╦═══════╦════════════════════╗
║ id ║ Data  ║ SnapshotGrannyId   ║
╠════╬═══════╬════════════════════╣
║ Y  ║ Kim   ║ X                  ║
╚════╩═══════╩════════════════════╝
Table ChildSnapshot:  
╔════╦═══════╦════════════════════╗
║ id ║ Data  ║ SnapshotParentId   ║
╠════╬═══════╬════════════════════╣
║ Z  ║ North ║ Y                  ║
╚════╩═══════╩════════════════════╝
This is my stored procedure:
Parameters
@tvpGrandparents -- columns: Data and OrigId
@tvpParents      -- columns: Data and GrannyId (and ???)
@tvpChildren     -- columns: Data and ParentId (and ???)
BEGIN
-- Works fine for GrandParentSnapshot, especially because there is an OrigId column in the table schema
DECLARE @InsertedGrannies TABLE( snapGranId, origId)
INSERT INTO GrandParentSnapshot (Data, OrigId)
OUTPUT Inserted.Id, Inserted.OrigId INTO @InsertedGrannies
SELECT Data, OrigId FROM @tvpGrandparents 
-- Insert Also works fine for ParentSnapshot
INSERT INTO ParentSnapshot (Data, OrigId)
SELECT parents.Data, insertedGrannies.snapGranId FROM @InsertedGrannies insertedGrannies
JOIN @tvpParents parents ON insertedGrannies.origId = parents.GrannyId
-- How do I do it for the ChildSnapshot??
-- I don't know how to come up with the SnapshotParentId
-- Is there anything I can OUTPUT from the Insert of ParentSnapshot table for me to wire up some link?
-- temp tables? any other ideas?
END
Hope someone can give some suggestion...sorry for my length question.