Sorry about the title. I could not think of a way to sum up my problem in a short sentence.
In a select statement, the table has a column of Active Directory ID's. I need to use a subquery to get the full names for the ADID's. I came up with the following code to query ADSI and get what I need:
SELECT givenName + ' ' + sn AS fullName
FROM OPENROWSET(
'ADSDSOObject', 'adsdatasource'; 'myDomain\jsmith'; 'myPassword',
'SELECT givenname, sn FROM ''LDAP://my.company.com'' WHERE objectClass = ''user'' AND SAMAccountName = ''stennell''')
That's cool, but I need to parameterize the ID, Password, and SAMAccountName value. Since the OPENRECORDSET requires literal strings, I can't concatenate strings & parameters. I must use dynamic SQL. So here's the new code:
SET @sql = 'SELECT givenName + '' '' + sn AS fullName ' + 'FROM OPENROWSET(''ADSDSOObject'', ''adsdatasource''; ''US\' + @authADID + '''; ''' + @authPWD + ''',' +
'''SELECT givenName, sn FROM ''''LDAP://us.ups.com'''' WHERE objectClass = ''''user'''' AND SAMAccountName = ''''' + @searchADID + ''''''')'
EXEC sp_executesql @sql
That works, so I wrap it up into a stored procedure. But I can't use EXEC in a query. Some google searching told me I needed to put the code in a Scalar-Valued function. So I tried that, but got this error when trying to create the function:
Only functions and some extended stored procedures can be executed from within a function.
So then more google searching told me to create a SQL CLR Function in Visual Studio. But I don't have the template all the tutorials told me to choose (SQL CLR C# User Defined Function). I have SQL Tools for VS installed, but still no templates.
I need to do something like this to get the result I need:
LEFT OUTER JOIN (SELECT fullName FROM (EXEC usp_queryADSI 'jsmith','myPassword', TIV.UserID)) AS AD
ON TIV.UserID = AD.ADID
Obviously, that doesn't work because you can't use EXEC like that. But I've hit a brick wall. Hoping someone can shed some light.