title: TSQL: How to get a list of groups that a user belongs to in Active Directory
body: <p>I have two queries that retrieve all groups and all users in a domain, <code>Mydomain</code></p>
  
  <pre><code>--; Get all groups in domain MyDomain
  select  *  
  from    OpenQuery(ADSI, '
      SELECT  samaccountname,mail,sn,name, cn, objectCategory
      FROM    ''LDAP://Mydomain/CN=users,DC=Mydomain,DC=com'' 
      WHERE   objectCategory=''group'' 
      ORDER BY cn
      ')
  
  --; Get all users in domain MyDomain
  select  *  
  from    OpenQuery(ADSI,'
      SELECT objectCategory, cn, sn, mail, name, department,samaccountname
      FROM ''LDAP://Mydomaindomain/CN=users,DC=Mydomain,DC=com'' 
      WHERE objectCategory=''user'' 
      ORDER BY cn
      ')
  --  where   samaccountname='mylogin'
  </code></pre>
  
  <p>What I would like to find out is, <br /></p>
  
  <p><strong>How do you retrieve a list of all groups in <code>MyDomain</code> that a particular user belongs to?</strong></p>
  
  <p><strong>[UPDATE]</strong> I was able to get the opposite result <br />
  Given the group name, retrieve all users</p>
  
  <pre><code>select  *  
  from    OpenQuery(ADSI,
      'SELECT objectCategory, cn, sn, mail, name, department
      FROM ''LDAP://Mydomain/CN=users,DC=wl-domain,DC=com'' 
      WHERE MemberOf=''cn=_____GROUPNAME_____,CN=users,DC=Mydomain,DC=com''
      ORDER BY cn' 
      )
  </code></pre>