This is for SQL DBAs to capture information on a server on which they have System Admin rights. It is not for hacking other peoples servers. This is for migrating an instance to a new server.
Set NoCount On
Declare @databasename VarChar(45)
Declare @sqlstmt nVarChar(max)
Set @sqlstmt = ''
Declare curDatabases Cursor Read_Only For
Select Name
From master.sys.databases With(NoLock)
Where source_database_id Is Null
And [state] = 0
Open curDatabases
Fetch Next From curDatabases
Into @databasename
While @@FETCH_STATUS = 0
Begin
--
Select @sqlstmt = @sqlstmt + 'SELECT ''Execute As Login = ''''corp\svc-sqlsrvcnp''''''' + Char(13)
Select @sqlstmt = 'SELECT ''Execute As Login = ''''corp\svc-sqlsrvcnp''''''' + Char(13)
+ 'UNION ALL' + Char(13)
+ 'SELECT ''GO'' ''--Scripter'''+ Char(13)
+ 'SELECT ''USE [' + @databasename + ']'' ''--Scripter''' + Char(13)
+ 'UNION ALL' + Char(13)
+ 'SELECT ''GO'' ''--Scripter'''+ Char(13)
+ 'UNION ALL' + Char(13)
+ 'SELECT ''CREATE USER ['' + [name] + ''] FOR LOGIN ['' + name + ''] '' + ' + Char(13)
+ '
Case' + Char(13)
+ '
When default_schema_name Is Null Then ''''' + Char(13)
+ '
Else ''WITH DEFAULT_SCHEMA=['' + default_schema_name + '']''' + Char(13)
+ '
End ''Scripter''' + Char(13)
+ ' FROM [' + @databasename + '].[sys].[database_principals] With(NoLock)' + Char(13)
+ ' Where Type In(''S'',''G'',''U'')' + Char(13)
+ '
And name Not In(''sys'',''dbo'',''guest'',''INFORMATION_SCHEMA'')' + Char(13)
+ '
And name Not Like ''lumcoll%'' ' + Char(13)
--+ 'COLLATE DATABASE_DEFAULT' + char(13)
+ 'UNION ALL ' + Char(13)
+ 'Select ''Execute sp_AddRoleMember '''''' + roles.name + '''''', '''''' + users.name + '''''''' ''--Scripter''' + Char(13)
+ ' from [' + @databasename + '].sys.database_principals users With(NoLock) ' + Char(13)
+ ' inner join [' + @databasename + '].sys.database_role_members link With(NoLock) ' + Char(13)
+ ' on link.member_principal_id = users.principal_id' + Char(13)
+ ' inner join [' + @databasename + '].sys.database_principals roles With(NoLock) ' + Char(13)
+ ' on roles.principal_id = link.role_principal_id' + Char(13)
+ 'Where users.name <> ''dbo'' ' + Char(13)
+ '
And users.name Not Like ''lumcoll%'' ' + Char(13)
+ '
And roles.name Not Like ''lumaudit%'' ' + Char(13)
--+ 'COLLATE DATABASE_DEFAULT' + char(13)
Fetch Next From curDatabases Into @databasename
If @@FETCH_STATUS = 0
Select @sqlstmt = @sqlstmt + 'UNION ALL' + Char(13) + 'SELECT ''GO'' ''--Scripter'''+ Char(13)
Exec sp_executesql @sqlstmt
End
Close curDatabases
Deallocate curDatabases