Sql-server – Detecting Orphaned Users

sql server

We have exported Microsoft SQL 2014 server and rebuilt master DB. Users are missing now, so we need to detect orphaned users.

We have found article:

https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/troubleshoot-orphaned-users-sql-server?view=sql-server-ver15#:%7E:text=%20Identify%20orphaned%20users%20in%20those%20environments%20with,are%20user%20SID%27s%20in%20the%20user…%20More%20

It says to use code in user database:

SELECT dp.type_desc, dp.SID, dp.name AS user_name  
FROM sys.database_principals AS dp  
LEFT JOIN sys.server_principals AS sp  
    ON dp.SID = sp.SID  
WHERE sp.SID IS NULL  
    AND authentication_type_desc = 'INSTANCE';

What is this user database? Where the code should be run to detect orphaned users? Now the server logins are missing. How to get same users as in original database?

Best Answer

That might've been a little bit of poor wording on Microsoft's part but basically what they meant is run that query in the context of the database which you want to check if there are Orphaned Users for. So which ever database you run it under, it'll tell you only for that database of there are Orphaned Users.

They clarify that slightly, just below the example query they provide in the article you linked:

The output lists the SQL Server authentication users and corresponding security identifiers (SID) in the current database that are not linked to any SQL Server login.

So if you have 3 databases on your server, for example, then you'd need to run that query 3 times (once in the context of each database) to verify for all of them.