How can I get a list of element names from an XML value in SQL Server

You can do this cleanly with XQuery and a recursive CTE (no OPENXML):

DECLARE @xml xml
SET @xml="<a><b /><c><d /><d /><d /></c></a>";

WITH Xml_CTE AS
(
    SELECT
        CAST("https://stackoverflow.com/" + node.value('fn:local-name(.)',
            'varchar(100)') AS varchar(100)) AS name,
        node.query('*') AS children
    FROM @xml.nodes('/*') AS roots(node)

    UNION ALL

    SELECT
        CAST(x.name + "https://stackoverflow.com/" + 
            node.value('fn:local-name(.)', 'varchar(100)') AS varchar(100)),
        node.query('*') AS children
    FROM Xml_CTE x
    CROSS APPLY x.children.nodes('*') AS child(node)
)
SELECT DISTINCT name
FROM Xml_CTE
OPTION (MAXRECURSION 1000)

It’s not really doing much XQuery magic, but at least it’s all inline, doesn’t require any stored procedures, special permissions, etc.

Leave a Comment