Home Forums SQL Server 2008 T-SQL (SS2K8) Recusion on Group and their subGroups- how can I solve this problem? RE: Recusion on Group and their subGroups- how can I solve this problem?

  • Having some difficulty understanding what you're after, so here's my best guess.

    BEGIN TRAN

    CREATE TABLE [dbo].[groupsAssociation](

    [Id] [int] IDENTITY(1,1) NOT NULL,

    [GroupId] [int] NOT NULL,

    [GroupName] [varchar](250) NULL,

    [ParentGroupId] [bigint] NULL,

    [ParentGroupName] [varchar](250) NULL

    ) ON [PRIMARY]

    --Fixed sample data -> you missed "UNION ALL"

    INSERT INTO [dbo].[groupsAssociation]

    ([GroupId]

    ,[GroupName]

    ,[ParentGroupId]

    ,[ParentGroupName])

    SELECT 269, 'B1', 271, 'B' UNION ALL

    SELECT 270, 'B2', 271, 'B' UNION ALL

    SELECT 269, 'B1', 272, 'A' UNION ALL

    SELECT 272, 'A', 271, 'B' UNION ALL

    SELECT 271, 'B', 272, 'A' UNION ALL

    SELECT 273, 'C', NULL, NULL UNION ALL

    SELECT 274, 'D', NULL, NULL

    --Actual query

    SELECT GroupId, Groups

    FROM (SELECT GroupId,

    GroupName + ISNULL(',' + STUFF((SELECT ',' + GroupName

    FROM (SELECT children.GroupName, nodes.Id

    FROM [groupsAssociation] nodes

    --Get child ID

    OUTER APPLY (SELECT [ParentGroupId], [GroupId] AS childid, [GroupName]

    FROM [groupsAssociation] st

    WHERE nodes.[GroupId] = st.[ParentGroupId]) children) t2

    WHERE t2.Id = t1.Id

    FOR XML PATH('')), 1, 1, ''),'') AS Groups

    FROM [groupsAssociation] t1) a

    GROUP BY GroupId, Groups

    ROLLBACK

    This returns: -

    GroupId Groups

    ----------- -----------------

    269 B1

    270 B2

    271 B,B1,B2,A

    272 A,B1,B

    273 C

    274 D


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/