How can I query Active Directory from SQL Server 2005?
Pretty general question but here are some pointers.
You need a linked server creating on the SQL Server that points to ADSI (Active Directory Service Interface) something like this will do it.
EXEC sp_addlinkedserver 'ADSI', 'Active Directory Services 2.5', 'ADSDSOObject', 'adsdatasource'
Then you can use the following sort of query.
SELECT *
FROM OPENQUERY(ADSI, 'SELECT sAMAccountName
FROM ''LDAP://DC=MyDC,DC=com,DC=uk''
WHERE objectCategory = ''Person''
AND objectClass = ''user'')
You'll need to set the LDAP:// line appropriately (ask your AD admin for the details) and be aware that distributed adhoc queries using OpenQuery are disabled by default in SQL Server. Once you have the above though it should be pretty easy to google for any particular variations.
Yes.
Linked server:
EXEC master.dbo.sp_addlinkedserver
@server = N'ADSI',
@srvproduct=N'Active Directory Services',
@provider=N'ADsDSOObject',
@datasrc=N'Servername.domain.com'
Query:
select * from openquery
(
ADSI,'SELECT name
FROM ''LDAP://Servername.domain.com''
WHERE objectCategory = ''Person'' AND objectClass = ''user''
')
There are lots of examples if you search linked server and LDPA on Google. I say this because LDAP can be quite complicated to work with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With