我有一个GetUsers
存储过程,如下所示。如果提供了@GroupId
或@GroupName
参数,那么我需要增强存储过程以确保仅返回属于匹配组的用户。
我创建了一个名为@GroupUserMatches
的特殊表变量,其中包含用于匹配用户组的UserId
/ GroupId
关联。我基本上可以将ELSE块中的SQL复制/粘贴到IF块中并稍微更新它以适应@GroupUserMatches
的连接,但我想知道是否有更优雅的方法来执行此操作?
一个问题是我希望避免在同一存储过程中对2个不同块中的相同SQL select进行更新。如果未提供@GroupId
或@GroupName
,则返回的用户列表应完全未按组进行过滤。
ALTER PROCEDURE [dbo].[GetUsers]
@DomainId uniqueidentifier = NULL,
@DomainName varchar(100) = NULL,
@NetworkUserId varchar(100) = NULL,
@UserPrincipalName varchar(100) = NULL,
@FirstName varchar(100) = NULL,
@LastName varchar(100) = NULL,
@EmailAddress varchar(255) = NULL,
@GroupId uniqueidentifier = NULL,
@GroupName varchar(500) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @GroupUserMatches TABLE
(
GroupId UNIQUEIDENTIFIER,
UserId UNIQUEIDENTIFIER
)
IF(@GroupId IS NOT NULL OR @GroupName IS NOT NULL)
BEGIN
INSERT INTO @GroupUserMatches (GroupId, UserId)
SELECT geue.GroupExtensionId, geue.UserExtensionId
FROM ADGroup adg
JOIN GroupExtension ge ON adg.Id = ge.ADGroupId
JOIN GroupExtensionUserExtension geue ON ge.Id = geue.GroupExtensionId
WHERE (@GroupId IS NULL OR ge.Id = @GroupId)
AND (@GroupName IS NULL OR adg.[Name] LIKE @GroupName + '%')
END
ELSE
BEGIN
SELECT
au.*,
0 HasExtendedSecurity
FROM
AllUsers au
JOIN
Domain d ON au.DomainName = d.[Name]
WHERE
(@DomainId IS NULL OR au.DomainId = @DomainId) AND
(@DomainName IS NULL OR au.DomainName = @DomainName) AND
(@NetworkUserId IS NULL OR au.NetworkUserId = @NetworkUserId) AND
(@UserPrincipalName IS NULL OR au.UserPrincipalName = @UserPrincipalName) AND
(@FirstName IS NULL OR au.FirstName LIKE @FirstName + '%') AND
(@LastName IS NULL OR au.LastName LIKE @LastName + '%' ) AND
(@EmailAddress IS NULL OR au.Email LIKE @EmailAddress + '%')
END
END