SQL合并父子数据列表

时间:2015-03-11 17:05:00

标签: sql sql-server merge parent-child master-detail

我有一个数据列表,我将其作为XML传递给存储过程。数据是Widget的列表,并且窗口小部件包含WidgetItem(父子数据)的列表。我想根据MERGE基于Widget的{​​{1}}子集进行操作。 ParentID的一些数据已更新,一些已被删除(因此从xml中删除),一些数据是新的。

更新的数据永远不会需要更新子数据,因为ParentID记录只能调整,而不能调整其中的项目(子数据)。 Insert将始终具有一个或多个子记录(WidgetItems)。

我似乎无法弄清楚如何在Widget中做到这一点,因为与处理数据层中的合并相比,这似乎是最好的方法。

这是我到目前为止所做的...我发表了一条评论,我被困住了:

MERGE

另外,如果我接近这个错误,可能会感谢替代解决方案,或者我可能需要在数据层处理此问题。

2 个答案:

答案 0 :(得分:1)

以下是应该回答您问题的更新代码。我已添加评论来解释发生了什么。希望它有意义。

正如您所说,所有传入的小部件的ParentID都是相同的,因此我将其视为参数而不是XML的元素

DECLARE @ParentID INT = 1

DECLARE @Widgets AS XML = 
N'<Widgets>
    <Widget>
        <WidgetID />
        <StartDate />
        <EndDate />
        <Details>
            <WidgetDetailItem>
                <WidgetDetailItemID></WidgetDetailItemID>
                <WidgetID/>
                <SomeID>4</SomeID>             
                <SomeData/>
            </WidgetDetailItem>
            <WidgetDetailItem>
                <WidgetDetailItemID></WidgetDetailItemID>
                <WidgetID/>
                <SomeID>323</SomeID>             
                <SomeData/>
            </WidgetDetailItem>
            <WidgetDetailItem>
                <WidgetDetailItemID></WidgetDetailItemID>
                <WidgetID/>
                <SomeID>1</SomeID>            
                <SomeData/>
            </WidgetDetailItem>
        </Details>
    </Widget>
    <Widget>
        <WidgetID>10</WidgetID>
        <StartDate>January 1, 2015</StartDate>
        <EndDate />
        <Details>
            <WidgetDetailItem>
                <WidgetDetailItemID></WidgetDetailItemID>
                <WidgetID/>
                <SomeID>4</SomeID>         
                <SomeData/>
            </WidgetDetailItem>
            <WidgetDetailItem>
                <WidgetDetailItemID></WidgetDetailItemID>
                <WidgetID/>
                <SomeID>99</SomeID>         
                <SomeData/>
            </WidgetDetailItem>
            <WidgetDetailItem>
                <WidgetDetailItemID></WidgetDetailItemID>
                <WidgetID/>
                <SomeID>6</SomeID>            
                <SomeData/>
            </WidgetDetailItem>
        </Details>
    </Widget>
</Widgets>';

--Used to hold the pseudoID -> WidgetID relationship for inserting the details
DECLARE @WidgetIds AS TABLE ([Action] varchar(10), PseudoID INT, WidgetID INT);

; 
--Use a CTE of the subset of data to be more performant. If we just went straight to the 
--merge we'd be operating on the entire table and that can have some major performance hits
WITH T AS (
              SELECT 
                     w.* 
              FROM
                     [dbo].[Widget] as w 
              WHERE
                     w.[ParentID] = @ParentID
)
MERGE INTO T 
USING (
        SELECT
            --Generate a pseudoid based on the order of the Widget elements so that we have some way of 
            --linking the detail records to the master
            row_number() OVER(ORDER BY PROPERTYFEED.P) PseudoID,
            'WidgetID' = P.value('WidgetID[1]', 'INT'),
            'ParentID' = @ParentID,
            'StartDate' = P.value('StartDate[1]', 'DATETIME'),
            'EndDate' = P.value('EndDate[1]', 'DATETIME')
        FROM
            @Widgets.nodes('/Widgets/Widget') PROPERTYFEED(P)
    ) 
    AS xmlIn
    (
           [PseudoID],
        [WidgetID],
        [ParentID],
        [StartDate],
        [EndDate]
    )
    ON
        T.[WidgetID] = xmlIn.[WidgetID]
    WHEN
        NOT MATCHED
    THEN
        INSERT 
        (
            [ParentID],
            [StartDate],
            [EndDate]
        ) 
        VALUES
        (
            xmlIn.[ParentID],
            xmlIn.[StartDate],
            xmlIn.[EndDate]
        )
    WHEN
        MATCHED AND (
            (T.[StartDate] <> xmlIn.[StartDate]) OR 
            (T.[EndDate] <> xmlIn.[EndDate]))
    THEN
        UPDATE SET
            T.[StartDate] = xmlIn.[StartDate],
            T.[EndDate] = xmlIn.[EndDate]
    WHEN
        NOT MATCHED BY SOURCE AND T.[DeletedDate] IS NULL 
    THEN
        UPDATE SET
            T.[DeletedDate] = GETDATE()         
OUTPUT  $action, xmlIn.PseudoID, INSERTED.WidgetID INTO @WidgetIds

;

--This is some magic to generate a temp table of numbers from 1 to COUNT(Widget)
--This is so we can reference the parent Widget row in the same order as the pseudoid generated above
--http://stackoverflow.com/a/1134379/4375845
;WITH Total(TotalWidgets) AS (SELECT COUNT(1) TotalWidgets FROM @Widgets.nodes('/Widgets/Widget') PROPERTYFEED(P))
       , Numbers(Num) as (
              SELECT 1 AS Num
              UNION ALL 
              SELECT Num+1 
              FROM Numbers
              JOIN Total t ON 1 = 1
              WHERE Num < t.TotalWidgets )
INSERT INTO WidgetDetailItem (WidgetID,SomeID,SomeData)
SELECT 
       w.WidgetID
       ,Details.SomeID
       ,Details.SomeData
FROM 
    (SELECT 
        P.value('WidgetDetailItemID[1]','int')  WidgetDetailItemID           
        , P.value('SomeID[1]','int') SomeID
        , P.value('SomeData[1]','varchar(5)') SomeData
        , n.Num AS PsuedoID
    FROM Numbers n
    --This is what gives us our pseudo ID to link to the row_number() function from the first merge statement
    CROSS APPLY @Widgets.nodes('/Widgets/Widget[sql:column("n.Num")]/Details/WidgetDetailItem') AS M(P)
    ) Details
JOIN @WidgetIds w on Details.PsuedoID = w.PseudoID
WHERE w.Action = 'INSERT' --We only want inserts by your spec

SELECT * FROM Widget;
SELECT * FROM WidgetDetailItem;

答案 1 :(得分:0)

我已将传入的XML反序列化为表格。这样就有机会验证XML字符串中的数据。

第1项:新的反序列化表格可以轻松过滤MERGE中包含的数据。

第2项:将数据插入子表必须单独调用。 MERGE只能在一个表上处理crud(创建更新删除)操作。

注意:MERGE将使用DESTINATION表中的所有记录。因此,当您未与Source匹配时,这将对表中未包含的所有记录起作用。