• You can also use the below : Here it lists all Orphaned users on existing DB and delete Ids and associated Schema .

    DECLARE @UserName varchar(100),

    @SQL as varchar(max)

    create table ##orphans (orphan varchar(128))

    -- 1)

    if substring(@@version, 1, 26) not in ('Microsoft SQL Server 2000', 'Microsoft SQL Server 2000')

    insert into ##orphans select u.name as 'Orphaned Users' from sys.server_principals l right join sys.database_principals u on

    l.sid = u.sid where l.sid is null and u.type not in ('A','R') and (u.name <> 'INFORMATION_SCHEMA' and u.name <> 'guest' and

    u.name <> 'system_function_schema' and u.name <> 'sys' and not db_name() + '.' + u.name= 'msdb.MS_DataCollectorInternalUser')

    else

    select u.name as 'Orphaned Users' from master..sysxlogins l right join sysusers u on l.sid = u.sid where l.sid is null and

    issqlrole <> 1 and isapprole <> 1 and (u.name <> 'INFORMATION_SCHEMA' and u.name <> 'guest' and u.name <> 'system_function_schema')

    DECLARE mycurs CURSOR FOR

    SELECT

    orphan

    FROM

    ##orphans

    OPEN mycurs

    FETCH NEXT FROM mycurs

    INTO @username

    WHILE @@FETCH_STATUS = 0

    BEGIN

    -- 2)

    BEGIN TRY

    EXEC sp_change_users_login @Action='update_one', @UserNamePattern=@UserName, @LoginName=@UserName

    END TRY

    BEGIN CATCH

    print @Username + ' does not exist as a Login. Deleting. '

    -- 3)

    BEGIN TRY

    SET @SQL = 'DROP SCHEMA [' + @UserName +']'

    EXEC (@SQL)

    END TRY

    BEGIN CATCH

    END CATCH

    -- 4)

    SET @SQL = 'DROP USER [' + @UserName + ']'

    Print @SQL

    EXEC (@SQL)

    END CATCH

    FETCH NEXT FROM mycurs

    INTO @username

    END

    CLOSE mycurs

    DEALLOCATE mycurs

    DROP TABLE ##orphans