Question : ADSI Query (linked server) to get computer name and OU's

Hi experts,

I have successfully added Active Directory as a linked server to my SQL Server 2005 server and am able to get a list of all Computers within my Workstations OU. However, within this OU I have sub-OUs and sub-sub-OUs which contain the actual computers.

When I run the below, I get the data like so:

LDAP://CN=PC37,OU=CSR,OU=Callcentre,OU=Workstations,OU=Staff,DC=mydomain,DC=co,DC=uk

If I remove the * in the query and replace it with Name then I get just the computer names, which is a good start. But what I really need is the results to be in separate columns as such:

Computer Name
OU1
OU2

and then strip off the rest (ou=Workstations,ou=Staff,DC=mydomain,DC=co,DC=uk)

Any ideas?

Thanks

Jon
Code Snippet:
1:
2:
3:
4:
5:
SELECT *
FROM OPENQUERY(ADSI,
'SELECT *
 FROM ''LDAP://ou=Workstations,ou=Staff,DC=mydomain,DC=co,DC=uk''
 WHERE objectCategory = ''computer'' AND  objectClass = ''computer'' ')

Answer : ADSI Query (linked server) to get computer name and OU's

ok i've had some coffee now and I see that the above code was not quite right.

Revised version below.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
drop table computers
create table Computers (computername varchar(20), OU1 varchar(20), OU2 varchar(20)) 
declare @rawldapstring varchar(255)
declare @str varchar(255)
declare @commapos int
declare @computername varchar(20)
declare @OU1 varchar(20)
declare @OU2 varchar(20)
declare @counter int 
set @counter=0 
set @rawldapstring=(select min([raw ldap string]) from test) 

while @counter<(select count (*) from test)
begin
	set @str=@rawldapstring 
	--find position of first comma
	set @commapos=charindex(',',@str) 
	--start after 11 characters and end at comma
	set @computername=(substring(@str,11,@commapos-11)) 

	--redefine string as what remains
	set @str =replace(@str,'LDAP://CN=' + @computername +',','') 

	--do roughly same process twice more
	set @commapos=charindex(',',@str)
	set @OU1=substring(@str,4,@commapos-4) 
	set @str =replace(@str,'OU=' + @OU1 +',','') 
	set @commapos=charindex(',',@str)
	set @OU2=substring(@str,4,@commapos-4) 
	insert into Computers values (@computername, @OU1, @OU2)
	set @counter=@counter+1 
	set @rawldapstring=(select min([raw ldap string]) from test where [raw ldap string]>@rawldapstring)
end 
select * from computers
Random Solutions  
 
programming4us programming4us