4

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?

d4nt
  • 15,475
  • 9
  • 42
  • 51

2 Answers2

5

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.

Dalex
  • 3,585
  • 19
  • 25
0

Try computed element constructors:

SELECT @data.query('
for $attr in /*/@*
return element {fn:local-name($attr)} {fn:string($attr)}
')
Leo Wörteler
  • 4,191
  • 13
  • 10
  • Thanks, but SQLServer errors with "Only constant expressions are supported for the name expression of computed element and attribute constructors." – d4nt Nov 18 '11 at 10:51