Return a calculated element name from a XML FLWOR query
-
03-03-2021 - |
Domanda
I have the following XML data in SQLServer 2008 R2
DECLARE @data XML
SET @data = '<root attr1="val1" attr2="val2" attr3="val3"/>'
I would like to get a list of the attribute names from root and output that as a list of elements, like this:
<root>
<attr1>val1</attr1>
<attr2>val2</attr2>
<attr3>val3</attr3>
</root>
I have been playing around with FLWOR queries to get what I want. So far I have this:
SELECT @data.query('
for $attr in /*/@*
return <test>{fn:string($attr)}</test>
')
Which is fine and is almost what I need, but when I try and do this...
SELECT @data.query('
for $attr in /*/@*
return <{fn:local-name($attr)}>{fn:string($attr)}</{fn:local-name($attr)}>
')
its not happy. It's doesn't seem to like anything other than a hard coded element name.
How can I return an element with a computed name?
Soluzione
According to Microsoft,
Right now, we only support constant expressions for the name expression of computed element and attribute constructors. The work around is building dynamic sql to cancat in the attribute name.
Altri suggerimenti
Try computed element constructors:
SELECT @data.query('
for $attr in /*/@*
return element {fn:local-name($attr)} {fn:string($attr)}
')