Tuesday 23 June 2015

Auto fix users after restore database in sql server

We need to create user first and then will have to fix the user permission.
So 1st we will use current database in query editor
and then will run given syntax

select 'EXEC sp_change_users_login ''Auto_Fix'', '''+ name +'''' from sysusers
where issqluser = 1
  and   (sid is not null and sid <> 0x0)
  and   (len(sid) <= 16)
  and   suser_sname(sid) is null
order by name


Now execute the result and fix all user privileges in Sql server database.

Reference


Other Information

--Get all Orphaned logins user in sql server database
select
    dp.name [user_name]
    ,dp.type_desc [user_type]
    ,isnull(sp.name,'Orhphaned!') [login_name]
    ,sp.type_desc [login_type]
from  
    sys.database_principals dp
    left join sys.server_principals sp on (dp.sid = sp.sid)
where
    dp.type in ('S','U','G')
    and dp.principal_id >4
order by sp.name


First, make sure that this is the problem. This will lists the orphaned users:
EXEC sp_change_users_login 'Report'

If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'

If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'