2013-01-16 35 views
2

XML 1TSQL代碼來同步兩個XML文檔

<Team> 
    <Players> 
    <Player id="1" timestamp="11/03/2012 08:10:12">30</Player> 
    <Player id="2" timestamp="11/02/2012 09:11:12">40</Player> 
    <Players> 
</Team> 

XML 2

<Team> 
    <Players> 
    <Player id="1" timestamp="11/02/2012 09:10:12">10</Player> 
    <Player id="2" timestamp="11/03/2012 10:11:12">20</Player> 
    <Player id="3" timestamp="11/03/2012 13:00:00">50</Player> 
    <Players> 
</Team> 

OUTPUT當我們合併基於時間戳元件上的上述兩個個XML:

<Team> 
    <Players> 
    <Player id="1" timestamp="11/02/2012 09:10:12">30</Player> 
    <Player id="2" timestamp="11/03/2012 10:11:12">20</Player> 
    <Player id="3" timestamp="11/03/2012 13:00:00">50</Player> 
    <Players> 
</Team> 

任何人都可以請幫我與T-SQL代碼來做到這一點在SQL Server 2005/2008

+0

@marc_s - 看起來'id'的後面一個會覆蓋之前的一個。 –

回答

2

使用帶有兩個嵌套的CTE的這種方法,你可以親近 - 但不是所有的方式:

DECLARE @XML1 XML = '<Team> 
    <Players> 
    <Player id="1" timestamp="11/03/2012 08:10:12">30</Player> 
    <Player id="2" timestamp="11/02/2012 09:11:12">40</Player> 
    </Players> 
</Team>' 

DECLARE @XML2 XML = '<Team> 
    <Players> 
    <Player id="1" timestamp="11/02/2012 09:10:12">10</Player> 
    <Player id="2" timestamp="11/03/2012 10:11:12">20</Player> 
    <Player id="3" timestamp="11/03/2012 13:00:00">50</Player> 
    </Players> 
</Team>' 

-- extract the ID, Timestamp and node values from both XML variables 
;WITH CTE AS 
(
SELECT 
    ID = P1.value('@id', 'int'), 
    TS = P1.value('@timestamp', 'datetime2'), 
    NodeValue = P1.value('(.)[1]', 'int') 
FROM @XML1.nodes('/Team/Players/Player') AS XTbl1(P1) 

UNION 

SELECT 
    ID = P2.value('@id', 'int'), 
    TS = P2.value('@timestamp', 'datetime2'), 
    NodeValue = P2.value('(.)[1]', 'int') 
FROM @XML2.nodes('/Team/Players/Player') AS XTbl2(P2) 
), 
-- partition and sequentially number the result, so that the newest 
-- (most recent) item can be extracted 
CTE2 AS 
(
    SELECT ID, TS, NodeValue, 
     RowNum = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY TS DESC) 
    FROM CTE 
) 
SELECT 
    ID AS '@id', 
    TS AS '@timestamp', 
    NodeValue AS 'text()' 
FROM CTE2 
WHERE RowNum = 1 
FOR XML PATH('Player'), ROOT('Players') 

結果是這樣的輸出:

<Players> 
    <Player id="1" timestamp="2012-11-03T08:10:12">30</Player> 
    <Player id="2" timestamp="2012-11-03T10:11:12">20</Player> 
    <Player id="3" timestamp="2012-11-03T13:00:00">50</Player> 
</Players> 
+0

thk你的解決方案。我會盡力讓你知道結果。 – user1745679

+0

hi marc,如果我在輸入xml中使用id ='football'o/p xml show id ='f'只有一個字母表。並在o/p xml中添加時間戳記,還有額外的字母't'。你能幫我解決這個問題嗎? – user1745679