Primarily, I needed to retrieve a list of users who are members of a particular group, in SQL Server. I did managed to find something on the net, which is working perfectly. Solution is as shown:
CREATE PROCEDURE [dbo].[NES_GetADGroupMembers]
(@groupName VARCHAR(max))
AS
BEGIN
CREATE TABLE #MemberOfGroups
(
groupName varchar(400),
cn varchar(400),
displayName varchar(400)
)
SET NOCOUNT ON
DECLARE @t varchar(100), @t2 varchar(1000),
@ot varchar (4000), @tt varchar (4000);
DECLARE gC CURSOR FOR
SELECT cn, distinguishedName
FROM openquery (ADSI, 'SELECT cn, distinguishedName
FROM ''''LDAP://Mydomaindomain/CN=users,DC=Mydomain,DC=com''''
WHERE objectCategory = ''group''')
OPEN gC
FETCH NEXT FROM gC INTO @t, @t2
WHILE @@FETCH_STATUS = 0
BEGIN
SET @ot = '''SELECT cn, displayName
FROM ''''LDAP://Mydomaindomain/CN=users,DC=Mydomain,DC=com''''
WHERE objectCategory = ''''Person'''' AND objectClass = ''''user''''
AND memberOf=''''' + @t2 + '''''';
SET @tt = 'select '+ ''''+@t+'''' +' As groupName, cn, displayName from openquery(ADSI,'+ @ot +''') order by cn'
INSERT INTO #MemberOfGroups (groupName, cn, displayName)
EXEC (@tt)
FETCH NEXT FROM gC INTO @t, @t2
END
CLOSE gC
DEALLOCATE gC
SELECT
groupName, displayName
FROM
#MemberOfGroups
For now, its just working fine, returning the users of the entered group.
However, I have a new request, whereby a group can have other 'groups' as member, just like the users.
I tried updating my filter in the WHERE condition to include objectClass = ''group''
, but it's not working.
Anyone knows a bit about these queries and can help me retrieve the groups (members of the input group) also?
OR
statement with groups, but in vain. – Roos