how to COPY Attribute value in a new attribute
How to copy data of attribute to new attribute in the same column in sql
original data
<root>
<child attr='hello'></child>
</root>
Result 1
<root>
<ch开发者_开发问答ild attr='hello' attr2='hello'></child>
</root>
Result 2(with a modification)
<root>
<child attr='hello' attr2='**H**ello **W**orld'></child>
</root>
I want to do this only through SQL XML Xquery
I'm not sure I follow what you're wanting exactly in the second result, but I'll take a stab at it: the first example below would produce your result #1 (I've put your original data in test.xml and assumed in your real data that 'child' and 'attr' might be repeated):
<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>
It could be modified to put a different value in, like in result #2, like the below:
<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>
Hope that helps.
Assuming that we can use XSLT, I would do it like this:
<?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>
Or, if you want the modification in Result 2, replace <xsl:template match="child">
with the following:
<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>
DECLARE @xmlData table (
data xml
)
INSERT INTO @xmlData(data)
VALUES ('<root>
<child attr="hello"></child>
</root>')
.modify()
performs all operations
UPDATE @xmlData
SET data.modify('insert (attribute attr2 {"hello"}) into (/root/child)[1]')
Verify that the data is correct
SELECT *
FROM @xmlData
UPDATE @xmlData
SET data.modify('replace value of (/root/child/@attr2)[1] with "**H**ello **W**orld" ')
Verify that the data is correct
SELECT *
FROM @xmlData
精彩评论