October 16, 2007

Fixing orphan logins on SQL Server 2005

Ever restored a backup that didn't include database logins, winding up with a lot of orphan logins? Here's a way out:

To set "targetUserNewLogin" as the new login for user "targetUser", run the following stored procedure (you can leave the first parameter unchanged):
sp_change_users_login 'update_one', 'targetUser','targetUserNewLogin'

If you need to get the list of users without logins:
SELECT * FROM sysusers
WHERE issqluser = 1 AND (sid IS NOT NULL AND sid <> 0x0)
AND suser_sname(sid) IS NULL


If you need to delete schema ownership:

SELECT s.* FROM sys.schemas AS s
INNER JOIN sys.database_principals AS dp ON dp.principal_id = s.principal_id
WHERE dp.[name] = 'someUser';

SELECT s.[name] as schemaname, o.[name] AS objectname, o.type_desc
FROM sys.objects AS o
INNER JOIN sys.schemas AS s ON s.schema_id = o.schema_id
INNER JOIN sys.database_principals AS dp ON dp.principal_id =s.principal_id
WHERE dp.[name] = 'someUser'
ORDER BY s.[name], o.type_desc, o.[name];

DROP SCHEMA someUser;

No comments: