Given the following dataset, I want the data grouped by Name, but the values of RoleID, RoleName, PermissionID, and PermissionName to be put together as a single XML value:
Name RoleID RoleName PermissionID PermissionName
--------------- ----------- ------------- ------------ ---------------
User 1 2 Super User 1 View
User 1 2 Super User 2 Create
User 1 2 Super User 3 Edit
User 1 2 Super User 4 Delete
User 1 3 Report User 17 Execute
So, the output I am trying to get to, should look something like this:
Name Roles
------------ -------------------------------------------------------
User 1 <Roles>
<Role id="2" name="Super User">
<Permissions>
<Permission id="1" name="View" />
<Permission id="2" name="Create" />
<Permission id="3" name="Edit" />
<Permission id="4" name="Delete" />
</Permissions>
</Role>
<Role id="3" name="Report User">
<Permissions>
<Permission id="17" name="Execute" />
</Permissions>
</Role>
</Roles>
I have tried the following, but it creates a Role row for each entry in the dataset:
SELECT
U.[ID] as [Name]
, CONVERT(xml, (
SELECT
R.[ID] as '@id'
, R.[Name] as '@name'
, CONVERT(xml, (
SELECT
P.[ID] as '@id'
, P.[Name] as '@name'
FOR XML PATH('Permission')
)) as [Permissions]
FOR XML PATH('Role'), ROOT('Roles')
)) as [Roles]
FROM User U
LEFT JOIN UserRoles UR ON
U.[ID] = UR.[UserID]
LEFT JOIN Role R ON
UR.[RoleID] = R.[ID]
LEFT JOIN RolePermissions RP ON
R.[ID] = RP.[RoleID]
LEFT JOIN Permission P ON
RP.[PermissionID] = P.[ID]
WHERE
U.[ID] = 1234