Question : Query on field of type XML – Top-level attribute nodes are not supported
set @x = ‘
Ae>
Jim
Joe
Be>
Sally
George>
‘
select
t.c.query(‘./UserName’).value(‘.’,’varchar(20)’) ,
t.c.query(‘../CompanyName’).value(‘.’,’varchar(20)’)
from @x.nodes(‘/root/Company/User’)as t(c)
This query works, but How would I get the ID attribute from the company element in the result set as well, my attempts lead to the following error:
‘ XQuery [value()]: Top-level attribute nodes are not supported. ‘
Thanks
Solution: Query on field of type XML – Top-level attribute nodes are not supported
Yep…this is where it becomes a lot more complicated. Two ways to solve it…one would be to use a FLWR query to get the value. The other would be to use a subquery to do it….
declare @x xml
set @x = ‘
Ae>
Jim
Joe
Be>
Sally
George>
‘
select
t.c.query(‘./UserName’).value(‘.’,’varchar(20)’) ,
t.c.query(‘../CompanyName’).value(‘.’,’varchar(20)’),
(
select
t1.c1.value(‘@ID’, ‘varchar(10)’)
from @x.nodes(‘/root/Company’)as t1(c1)
where t1.c1.query(‘.//CompanyName’).value(‘.’, ‘varchar(10)’) =
t.c.query(‘../CompanyName’).value(‘.’,’varchar(20)’)
)
from @x.nodes(‘/root/Company/User’)as t(c)