ALTER PROCEDURE [dbo].[usp_ShowUserRole]
AS
BEGIN
DECLARE @px INT = 0
DECLARE @dbname VARCHAR(max)
DECLARE @sql VARCHAR(MAX)
IF OBJECT_ID('tempdb..#dbs', 'U') IS NOT NULL
DROP TABLE #dbs
IF OBJECT_ID('tempdb..#userRole', 'U') IS NOT NULL
DROP TABLE #userRole
IF OBJECT_ID('tempdb..#execsql', 'U') IS NOT NULL
DROP TABLE #execsql
CREATE TABLE #userRole
(
id INT IDENTITY(1, 1) ,
dbname VARCHAR(60) ,
[user] VARCHAR(60) ,
userRole VARCHAR(60)
)
CREATE TABLE #execsql
(
id INT IDENTITY(1, 1) ,
esql VARCHAR(200)
)
SELECT id = IDENTITY( INT ,1,1 ),
name
INTO #dbs
FROM master.sys.databases db
WHERE db.database_id > 4
AND db.name NOT IN ( 'dbcenter','ReportServer','ReportServerTempDB','TargetDB','InitiatorDB' )
WHILE ( @px < ( SELECT MAX(id)
FROM #dbs
) )
BEGIN
SELECT TOP 1
@dbname = #dbs.name
FROM #dbs
SET @sql = 'use ' + @dbname + ' SELECT ' + '''' + @dbname
+ ''''
+ ' as ''dbname'', a.name as ''user'' ,c.name as ''userRole'' from '
+ @dbname + '.sys.sysusers a inner join ' + @dbname
+ '.sys.sysmembers b ON a.uid = b.memberuid inner join '
+ @dbname
+ '.sys.database_principals c ON b.groupuid = c.principal_id where a.name not in (''dbo'',''sys'')'
INSERT INTO #userRole
EXEC ( @sql
)
SET @px = @px + 1
DELETE #dbs WHERE name = @dbname
END
--SELECT * FROM #userRole
INSERT INTO #execsql
SELECT 'use ' + dbname + ' exec sp_addrolemember '
+ userRole + ',' + [user]
FROM #userRole
SELECT *
FROM #execsql
END