-- to translate the SID in AD format (e.g. from the NAV table "Windows Login") to binary format CREATE FUNCTION [dbo].[fn_StringToSID] ( @xStrSid VARCHAR(100) ) RETURNS VARBINARY(100) AS BEGIN DECLARE @xBinSid VARBINARY(100) SET @xBinSid = CAST(CAST(SUBSTRING(@xStrSid , 3,1) AS TINYINT) AS VARBINARY) SET @xBinSid = @xBinSid + 0x05 SET @xBinSid = @xBinSid + CAST(CAST(SUBSTRING(@xStrSid , 5,1) AS TINYINT) AS BINARY(6)) SET @xStrSid = SUBSTRING(@xStrSid,7,LEN(@xStrSid)-6) DECLARE @oneInt BIGINT WHILE CHARINDEX('-',@xStrSid) > 0 BEGIN SET @oneInt = CAST(SUBSTRING(@xStrSid,1,CHARINDEX('-',@xStrSid)-1) AS BIGINT) SET @xBinSid = @xBinSid + CAST(REVERSE(CAST(@oneInt AS VARBINARY)) AS VARBINARY(4)) SET @xStrSid = SUBSTRING(@xStrSid,CHARINDEX('-',@xStrSid)+1,LEN(@xStrSid)) END SET @oneInt = CAST(@xStrSid AS BIGINT) SET @xBinSid = @xBinSid + CAST(REVERSE(CAST(@oneInt AS VARBINARY)) AS VARBINARY(4)) -- select @xBinSid , suser_sname(@xBinSid) RETURN ( @xBinSid ) END -- to translate SID in binary format to AD format CREATE FUNCTION [dbo].[fn_SIDToString] ( @BinSID AS VARBINARY(100) ) RETURNS VARCHAR(100) AS BEGIN IF LEN(@BinSID) % 4 <> 0 RETURN(NULL) DECLARE @StringSID VARCHAR(100) DECLARE @i AS INT DECLARE @j AS INT SELECT @StringSID = 'S-' + CONVERT(VARCHAR, CONVERT(INT, CONVERT(VARBINARY, SUBSTRING(@BinSID, 1, 1)))) SELECT @StringSID = @StringSID + '-' + CONVERT(VARCHAR, CONVERT(INT, CONVERT(VARBINARY, SUBSTRING(@BinSID, 3, 6)))) SET @j = 9 SET @i = LEN(@BinSID) WHILE @j < @i BEGIN DECLARE @val BINARY(4) SELECT @val = SUBSTRING(@BinSID, @j, 4) SELECT @StringSID = @StringSID + '-' + CONVERT(VARCHAR, CONVERT(BIGINT, CONVERT(VARBINARY, REVERSE(CONVERT(VARBINARY, @val))))) SET @j = @j + 4 END RETURN ( @StringSID ) ENDYou run those scripts in the Master database, so it's easily accessible from any query.
-- sample script to show the link between SID in "Windows Login" and sys.syslogins SELECT SID as NAVSID,[dbo].[fn_StringToSID](SID) as SQLSID FROM [Demo Database NAV (6-0)].[dbo].[Windows Login] SELECT SL.sid as SQLSID, SL.name as SQLNAME, WL.SID as NAVSID FROM sys.syslogins as SL JOIN [Windows Login] as WL ON SL.sid = [dbo].[fn_StringToSID](WL.SID) SELECT * From [Windows Login] WHERE [Windows Login].SID = dbo.fn_SIDToString(SUSER_SID())
Comments
RIS Plus, LLC
Just replace YOUR_NAV_DATABASE and you are good to go