How to get the ROOT node name from SQL Server
Asked Answered
W

2

15

I have a table where ID is integer and XML is XML data type.

ID   XML
----------------------
1    <Form1>...</Form1>
2    <Form1>...</Form1>
3    <Form2>...</Form2>
4    <Form3>...</Form3>

How do I get the result below?

ID   XML
-------------
1    Form1
2    Form1
3    Form2
4    Form3
Wellchosen answered 6/9, 2013 at 7:39 Comment(0)
D
33

Use the local-name() function

 select ID, XML.value('local-name(/*[1])','varchar(100)')
 from yourtable
Darwindarwinian answered 6/9, 2013 at 7:47 Comment(0)
C
2

Try this

DECLARE @xml as xml
SET @xml = '<Form1>...</Form1>'
SELECT Nodes.Name.query('local-name(.)') FROM @xml.nodes('//*') As Nodes(Name)
Contribute answered 6/9, 2013 at 7:48 Comment(1)
We were using this method, but we ran into issues with "local-name(.)" being a slow operation. replacing the . with /*[1] as indicated in the above answer gave us better performance.Hacking

© 2022 - 2024 — McMap. All rights reserved.