如何在SQL Server的同一张表中显示XML节点内容从一列到另一列?

时间:2018-06-26 17:01:51

标签: sql sql-server xml

一列包含XML的整个正文。我想采用该XML并从特定节点获取内容,并将其放入同一表的另一列中。在SQL Server中执行此操作的最佳方法是什么?

我尝试使用计算列,但不确定如何创建公式来隔离单个XML节点。

谢谢!

1 个答案:

答案 0 :(得分:4)

像这样吗?

DECLARE @tbl TABLE (ID INT IDENTITY, BodyXML XML, ContentXML XML, MergedXML XML);
INSERT INTO @tbl VALUES
 (N'<root>
    <!-- This can be a fully blown document, we want to insert into "inner node" -->
    <innerNode>
    </innerNode>
    </root>'
 ,N'<root>
    <Content attr="yes">This we want to embed</Content>
    <Content attr="no">this not</Content>
    <Content attr="yes">but this</Content>
    </root>'
  ,NULL);

UPDATE @tbl SET MergedXML=BodyXML; --pre set all with the body

WITH updateableCTE AS
(
    SELECT MergedXML AS TargetColumn
          ,ContentXML.query('/root/Content[@attr="yes"]') AS EmbedThis 
    FROM @tbl 
)
UPDATE updateableCTE SET TargetColumn.modify(N'insert sql:column("EmbedThis") into (/root/innerNode)[1]');

SELECT * FROM @tbl; 

这是新的“ MergedXML”:

<root>
  <!-- This can be a fully blown document, we want to insert into "inner node" -->
  <innerNode>
    <Content attr="yes">This we want to embed</Content>
    <Content attr="yes">but this</Content>
  </innerNode>
</root>