tsql代码同步两个xml文件

时间:2013-01-16 18:54:07

标签: sql tsql sql-server-2005

xml 1

<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>

基于timestamp元素合并上述两个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中执行此操作

1 个答案:

答案 0 :(得分: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>