具有表值参数和分层数据的SQL存储过程

时间:2019-02-18 16:33:42

标签: tsql stored-procedures table-valued-parameters

背景: 我有一个存储过程,其目的是将“活动表”中的数据“快照”到“快照表”中。 由于性能原因,我传递了表值参数。 “活动表”中的数据本质上是分层的(祖父母/子女)。 到目前为止,数据库模式是固定的。 实际上,如果我可以随意添加一列,则很容易解决此问题,但是现在不允许这样做。

问题: 目前,我被卡在ChildSnapshot表上。我不知道如何在给定数据库模式的情况下获取SnapshotParentId的值。 我不允许在ParentSnapshot表中添加“ OrigParentId”。 请检查我存储的过程,看看我被卡住了。

这些就是“活动表”:
(我将A,B,C,X,Y,Z用作id列而不是数字,以轻松演示表之间的关系)

Table: GrandParent
╔════╦══════╗
║ id ║ Data ║
╠════╬══════╣
║ A  ║ Kris ║
╚════╩══════╝
Table: Parent
╔════╦══════╦══════════╗
║ id ║ Data ║ GrannyId ║
╠════╬══════╬══════════╣
║ B  ║ Kim  ║ A        ║
╚════╩══════╩══════════╝
Table Child
╔════╦═══════╦══════════╗
║ id ║ Data  ║ ParentId ║
╠════╬═══════╬══════════╣
║ C  ║ North ║ B        ║
╚════╩═══════╩══════════╝

这些是“实时”表,其中也包含我的预期结果:

Table GrandParentSnapshot:  
╔════╦═══════╦══════════╗
║ id ║ Data  ║ OrigId   ║
╠════╬═══════╬══════════╣
║ X  ║ Kris  ║ A        ║
╚════╩═══════╩══════════╝

Table ParentSnapshot:  
╔════╦═══════╦════════════════════╗
║ id ║ Data  ║ SnapshotGrannyId   ║
╠════╬═══════╬════════════════════╣
║ Y  ║ Kim   ║ X                  ║
╚════╩═══════╩════════════════════╝

Table ChildSnapshot:  
╔════╦═══════╦════════════════════╗
║ id ║ Data  ║ SnapshotParentId   ║
╠════╬═══════╬════════════════════╣
║ Z  ║ North ║ Y                  ║
╚════╩═══════╩════════════════════╝

这是我的存储过程:

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

希望有人可以提出一些建议...对不起我的长度问题。

0 个答案:

没有答案
相关问题