从T-SQL查询的子组中选择所有用户

时间:2019-06-10 10:49:23

标签: sql-server tsql

我有一个SQL Server表,其中包含用于在应用程序中定义用户权限的组和子组。我要完成的工作是基于分配给组的已使用ID从所有子组中选择所有用户ID。

SQL Server data

我已尝试使用此查询,但是它仅显示一级子组用户。

SET @UserIds =
    ISNULL(
        STUFF((SELECT ',' + CAST(tbl.UserID AS VARCHAR(MAX)) 
               FROM 
                   (SELECT grpUser.UserId AS UserID
                    FROM dbo.GroupUser grpUser
                    INNER JOIN (SELECT subGrp.Id, subGrp.GroupName
                                FROM dbo.Groups grp
                                INNER JOIN dbo.GroupUser guser ON grp.Id = guser.GroupId
                                                               AND guser.UserId = @UserId
                                INNER JOIN dbo.Groups subGrp ON grp.Id = subGrp.ParentGroupId) tbl ON grpUser.GroupId = tbl.Id) AS tbl
                FOR XML PATH('')), 1, 1, ''), '')

我正在努力获取所有子组中的用户ID。未定义子组数。有没有一种方法可以在sql中执行,还是应该将这一部分移至应用程序端?谢谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

最后,我想到了这段代码。谢谢提示。

declare @UserGroupId int;
       Set @UserGroupId = (Select GroupId from GroupUser gu 
                          left join dbo.Groups gr on gu.GroupId = gr.id
                          where UserId = @UserId and gr.IsDeleted = 0)

       declare @UsersGroups  Table (
       Id int not null,
       GroupName nvarchar(50) not null
        )

        ;WITH grp AS
        (
            SELECT Id, GroupName

            FROM Groups
            WHERE ParentGroupId = 1
            UNION ALL
            SELECT g.Id, g.GroupName
            FROM Groups g
            INNER JOIN dbo.GroupUser guser ON g.Id = guser.GroupId
            INNER JOIN grp ON g.ParentGroupId = grp.Id  
        )

        Insert into @UsersGroups    
        SELECT Id, GroupName
        FROM grp

        SET @UserIds =  ISNULL(STUFF(( SELECT   ',' + CAST(tbl.UserID AS VARCHAR(max)) FROM ( 
                            SELECT grpUser.UserId AS UserID FROM    dbo.GroupUser grpUser
                            INNER   JOIN ( SELECT * FROM @UsersGroups
                            ) tbl ON grpUser.GroupId = tbl.Id
                            ) AS tbl FOR XML PATH('') ), 1, 1, ''), '')