Google Custom Search

Monday, December 29, 2008

Script to fix Orphans user in all Databases

SET NOCOUNT ON
create table #fix_orphanusers(dbname varchar(50),username varchar(50),userid uniqueidentifier)

insert into #fix_orphanusers
Exec SP_MSForEachDB 'select ''?'' as DBName, name AS UserName, sid AS UserSIDfrom ?..sysuserswhere issqluser = 1 and(sid is not null and sid <> 0x0)and suser_sname(sid) is nullorder by name'

declare @dbname varchar(50)
declare @username varchar(50)
declare @cmd varchar(4000)

DECLARE fixoprhans_cursor CURSOR FOR
SELECT dbname,username from #fix_orphanusers

open fixoprhans_cursor
fetch next from fixoprhans_cursor into @dbname,@username

while @@fetch_status=0
begin
select @cmd = 'use '+@dbname+char(10)+'go'+char(10)+'sp_change_users_login ''update_one'','+''''+@username+''''+','+''''+@username+''''+char(10)+'go'
exec @cmd
fetch next from fixoprhans_cursor into @dbname,@username
end
close fixoprhans_cursor
deallocate fixoprhans_cursor

drop table #fix_orphanusers

No comments: