I have a table like this (simplified):
ID | Name | Parent
---------------------------------
1 | IND | NULL
2 | INS | 5
3 | CON
You can also do this without creating a separate function, by including the sub-query as an additional column that returns XML. For example, the following will return a hierarchical XML document containing users and their associated list of roles:
SELECT
FirstName, LastName,
CONVERT(XML,
(SELECT r.UserID, r.RoleID
FROM global.[UserRole] r
WHERE r.USerID = [user].UserID
FOR XML RAW ('Role'), ELEMENTS, root('Roles')
))
FROM global.[user]
FOR XML RAW ('User'), ELEMENTS, root('Users')