I have the following table
name | age | misc
------------------
david | 20 | foo
john | 30 | bar
And I want to convert it to the following XML:
<doc>
<field name="name" val="david" />
<field name="age" val="20" />
<field name="misc" val="foo" />
</doc>
<doc>
<field name="name" val="john" />
<field name="age" val="30" />
<field name="misc" val="bar" />
</doc>
I have below for one column for this work, however, if I try to add a second column for another fieldnode, I get an error:
Msg 9303, Level 16, State 1, Line 25
XQuery [query()]: Syntax error near 'name', expected '}'.
This is an example of what I'm trying to do and is ready to run in SQL Server Management Studio. I can not find much documentation on syntax and am pretty lost for ideas.
Any help is appreciated!
declare @MyData table (name varchar(200), age varchar(200), misc varchar(200))
insert into @MyData values('david', '20', 'foo')
insert into @MyData values('john', '30', 'bar')
SELECT (select * from @MyData as MyData for xml auto, type).query
(
' for $d in /MyData
return
<doc>{
<field name="name" val="{data($d/@name)}" />
}</doc>'
)
SELECT (select * from @MyData as MyData for xml auto, type).query
(
' for $d in /MyData
return
<doc>{
<field name="name" val="{data($d/@name)}" />
<field name="age" val="{data($d/@age)}" />
<field name="misc" val="{data($d/@misc)}" />
}</doc>'
)
source
share