查询所有数据库的数据库账号对应的DB Role

查询所有数据库的数据库账号对应的DB Role,可以直接将以下脚本拷贝使用:

--exec sp_helpuser
--select DB_Name()

--drop table #UserDB
--drop table #DB_Role

Create table #DB_Role
(
DBName varchar(100) null,
UserName varchar(100),
RoleName Varchar(1000),
LoginName Varchar(100),
DefDBName varchar(100),
DefSchemaName varchar(100),
UserID varchar(100),
SID varchar(1000))
Create table #UserDB
(name varchar(1000));
insert into #UserDB
            select name from sys.databases where name not in         
            (N'master', N'model', N'msdb', N'tempdb', N'distribution', N'DWDiagnostics', N'DWConfiguration', N'DWQueue', N'resource',N'ReportServer',N'ReportServerTempDB')
Declare @UserDB nvarchar(1000);
Declare DBrole_cursor cursor
            for
select * from #UserDB;
open DBrole_cursor;
fetch next from DBrole_cursor into @UserDB;
while @@FETCH_STATUS=0
begin
Declare @DBrole_SQL varchar(1000)
set @DBrole_SQL=
'use '+QUOTENAME(@UserDB,'[]')+';
insert into  #DB_Role
(
UserName,
RoleName,
LoginName,
DefDBName,
DefSchemaName,
UserID,
SID) exec sp_helpuser;
update #DB_Role set DBName='+''''+@UserDB+''''+' where DBName is null
'
print (@DBrole_SQL)
exec (@DBrole_SQL)
fetch next from DBrole_cursor into @UserDB;
end
close DBrole_cursor;
deallocate DBrole_cursor;

select * from #DB_Role

posted @ 2019-09-03 18:38  MarkL9527  阅读(397)  评论(0编辑  收藏  举报