Annoyingly you have to build the SQL string ahead of time to add a parameter value into it and then execute the OpenQuery using that string. You must execute all of it as you would a dynamic query EXEC sp_executeSQL ...
Here's what I came up with:
DECLARE @eid nvarchar(5), @username nvarchar(5), @Query nvarchar(MAX)
SELECT @eid='123'
SELECT @Query = N'SELECT sAMAccountName FROM OpenQuery(ADSI, ''SELECT sAMAccountName, employeeID FROM ''''LDAP://mydomain.com/DC=mydomain,DC=com'''' WHERE objectClass = ''''User'''' AND employeeID=' + @eid + ''')'
SELECT @Query
EXEC sp_executeSQL @Query, @username OUTPUT
PRINT @username
I may not have the output quite right. Another option you have is to insert the output of the EXEC sp_executeSQL
into a temptable and select the username from that value. For more info you can see this question.
Another option (and probably the easiest of all) is to move the WHERE
outside of the open query and filter after you get the results back like this:
DECLARE @eid nvarchar(5), @username nvarchar(5), @Query nvarchar(MAX)
SELECT @eid='123'
SELECT @username = sAMAccountName--, employeeID
FROM OpenQuery(AD, 'SELECT sAMAccountName, employeeID FROM ''LDAP://mydomain.com/DC=mydomain,DC=com'' WHERE objectClass = ''User''')
WHERE employeeID = @eid
PRINT @username