简体   繁体   中英

How can I display XML node content from one column into another column on the same table in SQL Server?

One column contains the entire body of XML. I would like to take that XML and grab the content from a specific node and place it into another column on the same table. What is the best way to do this in SQL Server?

I attempted to use a calculated column, but I'm not sure how I could create a formula to isolate a single XML node.

Thanks!

Something like this?

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; 

this is the new "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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM