So I have the following integrated R code which I use to be able to match stuff via regex without too much complication (what I want to do eventually is more complex than this example so regex is pretty much required, this is just the first step):
DECLARE @in_adcn nvarchar(500)
DECLARE @out_ou nvarchar(500)
SET @in_adcn = N'CN=Surname\, Firstname (asdf),OU=999,OU=Department2,OU=Fixed,OU=Fixed,DC=Fixed,DC=Fixed,DC=Fixed'
SET @out_ou = N''
-- Extract department name from AD OU string
EXEC sp_execute_external_script @language=N'R',
@script = N'
pat = "^.+OU=([^,]+),OU=Fixed,OU=Fixed,DC=Fixed,DC=Fixed,DC=Fixed$";
m <- gsub(pat, "\\1", regmatches(in_adcn1, gregexpr(pat, in_adcn1))[[1]]);
out_ou1 <- m;',
@params = N'@in_adcn1 varchar(500), @out_ou1 varchar(500) output',
@in_adcn1 = @in_adcn,
@out_ou1 = @out_ou OUTPUT
WITH RESULT SETS NONE;
SELECT @out_ou;
GO
This works fine, it returns exactly what I want from the AD distinguishedName string (in this case: "Department2").
Now I want that output string inside this SELECT query (the input string for the R script is acad.ADCn
):
SELECT
acad.ADCn,
(
--<here should be the code that returns the string from the R script above>
) AS Departmentname,
acad.NBAccountName,
acb.eMail
FROM
MyDB.dbo.AccountTable AS acad
LEFT JOIN
MyDB.dbo.AddressTable AS acb
ON
acad.[ObjectID]
= acb.[ObjectID]
So far I haven't managed to get this right yet. Any help would be greatly appreciated.