Friday, 7 April 2017

Remove Orphan users from the databases

CREATE TABLE #ORPHANS
(
RowID     int not null primary key identity(1,1),
DBNAME VARCHAR(100),
USERNAME VARCHAR(100),
CREATEDATE VARCHAR(100),
USERTYPE VARCHAR(100)
)

EXEC SP_MSFOREACHDB' USE [?]
INSERT INTO #ORPHANS
SELECT DB_NAME() DBNAME, NAME,CREATEDATE,
(CASE
WHEN ISNTGROUP = 0 AND ISNTUSER = 0 THEN ''SQL LOGIN''
WHEN ISNTGROUP = 1 THEN ''NT GROUP''
WHEN ISNTGROUP = 0 AND ISNTUSER = 1 THEN ''NT LOGIN''
END) [LOGIN TYPE] FROM sys.sysusers
WHERE SID IS NOT NULL AND SID <> 0X0 AND ISLOGIN =1 AND
SID NOT IN (SELECT SID FROM sys.syslogins)'

SELECT * FROM #ORPHANS

--Delete from #ORPHANS where USERNAME='dbo'

Declare @SQL as varchar (200)
Declare @DDBName varchar (100)
Declare @Orphanname varchar (100)
Declare @DBSysSchema varchar (100)
Declare @From int
Declare @To int
Select @From = 0, @To = @@ROWCOUNT
from #Orphans
--Print @From
--Print @To
While @From < @To
Begin
  Set @From = @From + 1
 
  Select @DDBName = DBName, @Orphanname = UserName from #Orphans
   Where RowID = @From

   BEGIN TRY
       EXEC sp_change_users_login @Action='update_one', @UserNamePattern=@orphanname,

@LoginName=@orphanname
   END TRY
   Begin Catch
   End Catch
     
   Set @DBSysSchema = '[' + @DDBName + ']' + '.[sys].[schemas]'
   print @DBsysSchema
   Print @DDBname
   Print @Orphanname
   set @SQL = 'If Exists (Select * from ' + @DBSysSchema
                          + ' where name = ''' + @Orphanname + ''')
    Begin
     Use ' + @DDBName
                                        + ' Drop Schema [' + @Orphanname + ']
    End'
   print @SQL
   Exec (@SQL)
   
    Begin Try

     Set @SQL = 'Use ' + @DDBName + ' Drop User [' + @Orphanname + ']'

Print ' Deleting User'+@orphanname
     Exec (@SQL)
       Print @sql
    End Try
    Begin Catch
    End Catch
       Print @orphanname
   Print @DDBName
End

DROP TABLE #ORPHANS

No comments:

Post a Comment