2

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>

当我们基于时间戳元素合并上述两个 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 中执行此操作

4

1 回答 1

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>
于 2013-01-16T19:27:56.503 回答