Alessandro Melandri

IT Project Manager, strimpello la chitarra, fotografo particolari insignificanti, studio la Lingua dei Segni Italiana. Follow me on Mastodon or Linkedin

Removing orphaned users from a SQLServer database

If you are using SQLServer probably you had to restore a database from a backup and got stuck with an orphaned user that was no more associated with a login.

Microsoft provides a stored procedure to remove this orphaned user.

exec sp_revokedbaccess 'Orphaned_User_Name'

You could get an error because the user still owns a schema. To find out which schema is bound with the user you can use this query

SELECT name FROM  sys.schemas 
WHERE principal_id = USER_ID('Orphaned_User_Name')

And then drop the orphaned user from the schema

ALTER AUTHORIZATION ON SCHEMA::SchemaName TO dbo
GO
DROP USER Orphaned_User_Name