I have a SQL Function that calls OpenQuery
to return the sAMAccountName
for a given @displayname
.
If I call the function, I get the error:
Cannot fetch a row from OLE DB provider "ADSDSOObject" for linked server "ADSI"
If I use a SQL select that calls the OpenQuery
, it works.
select sAMAccountName from OpenQuery (ADSI, 'SELECT sAMAccountName, displayname FROM ''LDAP://mydomain'' WHERE objectCategory=''user''') where displayname = 'Doug Kimzey'
The function below always returns the error.
ALTER FUNCTION [dbo].[cus_GetADLogin]
( @displayName varchar(64) )
RETURNS VARCHAR(128)
AS
BEGIN
declare @sAMAccountName varchar(128)
SET @sAMAccountName = (SELECT sAMAccountName FROM
OpenQuery (ADSI, 'SELECT sAMAccountName, displayname FROM ''LDAP://mydomain'' WHERE objectCategory=''user''') AD
where AD.displayName = @displayName)
RETURN @sAMAccountName
END
Would anyone know why the SELECT...OpenQuery
works outside of the function but fails when executed inside a function?
I have a SQL Function that calls OpenQuery
to return the sAMAccountName
for a given @displayname
.
If I call the function, I get the error:
Cannot fetch a row from OLE DB provider "ADSDSOObject" for linked server "ADSI"
If I use a SQL select that calls the OpenQuery
, it works.
select sAMAccountName from OpenQuery (ADSI, 'SELECT sAMAccountName, displayname FROM ''LDAP://mydomain'' WHERE objectCategory=''user''') where displayname = 'Doug Kimzey'
The function below always returns the error.
ALTER FUNCTION [dbo].[cus_GetADLogin]
( @displayName varchar(64) )
RETURNS VARCHAR(128)
AS
BEGIN
declare @sAMAccountName varchar(128)
SET @sAMAccountName = (SELECT sAMAccountName FROM
OpenQuery (ADSI, 'SELECT sAMAccountName, displayname FROM ''LDAP://mydomain'' WHERE objectCategory=''user''') AD
where AD.displayName = @displayName)
RETURN @sAMAccountName
END
Would anyone know why the SELECT...OpenQuery
works outside of the function but fails when executed inside a function?
- 1 Which dbms are you using? (The above code is very product specific.) – jarlh Commented Feb 17 at 18:11
- Microsoft SQL Server 2016 – Doug Kimzey Commented Feb 17 at 19:23
1 Answer
Reset to default 1Wouldn't this work?
ALTER FUNCTION [dbo].[cus_GetADLogin]
( @displayName varchar(64) )
RETURNS VARCHAR(128)
AS
BEGIN
declare @sAMAccountName varchar(128)
SELECT @sAMAccountName = sAMAccountName FROM
OpenQuery (ADSI, 'SELECT sAMAccountName, displayname FROM ''LDAP://mydomain'' WHERE objectCategory=''user''') AD
where AD.displayName = @displayName;
RETURN @sAMAccountName
END