2010-04-09 59 views
2

如何屬性的數據在同一列的SQL複製到新的屬性如何在一個新的屬性中複製屬性值

原始數據

<root> 
<child attr='hello'></child> 
</root> 

結果1

<root> 
<child attr='hello' attr2='hello'></child> 
</root> 

結果2(帶有修改)

<root> 
<child attr='hello' attr2='**H**ello **W**orld'></child> 
</root> 

我想只有通過SQL XML的Xquery

+0

我不想使用xslt – 2010-04-09 08:38:33

回答

0

假設我們可以使用XSLT來做到這一點,我會做這樣的:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 

    <xsl:output method="xml" indent="yes" omit-xml-declaration="no" /> 

    <xsl:template match="root"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="child"> 
     <xsl:copy> 
      <xsl:copy-of select="@*"/> 
      <xsl:attribute name="attr2"> 
       <xsl:value-of select="@attr"/> 
      </xsl:attribute> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

或者,如果你想在結果2修改,替換<xsl:template match="child">有以下幾點:

<xsl:template match="child"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:attribute name="attr2"> 
      <xsl:value-of> 
       <xsl:text>**H**ello **W**orld</xsl:text> 
      </xsl:value-of> 
     </xsl:attribute> 
    </xsl:copy> 
</xsl:template> 
+0

我只想通過SQL來完成此操作XML Xquery – 2010-04-14 10:34:22

1

我不知道我跟着你想究竟是什麼在第二個結果,但我會在它採取了刺:下面的第一個例子將產生你的結果#1 (我把你的或在的test.xml iginal數據和您的真實數據假設的「孩子」和「教師責任觀」可能會重複):

<root>{ 
    for $child in doc('test.xml')/root/* 
    return 
    element {name($child)} { 
     for $attr at $index in $child/@* 
     return (
     attribute {name($attr)} {$attr}, 
     attribute {concat(name($attr), 2)} {$attr} 
    ) 
    } 
}</root> 

它可以修改放在一個不同的值,如在結果#2,如如下:

<root>{ 
    for $child in doc('test.xml')/root/* 
    return 
    element {name($child)} { 
     for $attr at $index in $child/@* 
     return (
     attribute {name($attr)} {$attr}, 
     attribute {concat(name($attr), 2)} { 
      '**H**ello **W**orld' 
     } 
    ) 
    } 
}</root> 

希望有所幫助。

+0

我只想通過SQL XML Xquery – 2010-04-14 10:32:50

0
DECLARE @xmlData table (
    data xml 
    ) 


INSERT INTO @xmlData(data) 
VALUES ('<root> 
    <child attr="hello"></child> 
    </root>') 

.modify()執行的所有操作

UPDATE @xmlData 
SET data.modify('insert (attribute attr2 {"hello"}) into (/root/child)[1]') 

驗證數據是正確的

SELECT * 
FROM @xmlData 


UPDATE @xmlData 
SET data.modify('replace value of (/root/child/@attr2)[1] with "**H**ello **W**orld" ') 

驗證數據是正確的

SELECT * 
FROM @xmlData 

enter image description here