我被分配了一项我没有任何知识或经验的任务。我正在研究.NET解决方案,我需要使用SQL在sql中查询数据库的实例。对于实例中的每个数据库,我需要检索用户列表以及它们属于哪个角色。提前谢谢!
我在下面找到了这个脚本,但它需要管理员权限。
有没有办法在没有管理员权限的情况下执行此操作?
DECLARE @DB_USers TABLE (
DBName SYSNAME
,UserName SYSNAME
,AssociatedRole VARCHAR(max)
)
INSERT @DB_USers
EXEC sp_MSforeachdb 'use [?]
SELECT '' ? '' AS DB_Name
,CASE prin.NAME
WHEN '' dbo ''
THEN prin.NAME + '' (
'' + (
SELECT SUSER_SNAME(owner_sid)
FROM master.sys.databases
WHERE NAME = '' ? ''
) + ''
) ''
ELSE prin.NAME
END AS UserName
,isnull(USER_NAME(mem.role_principal_id), '''') AS AssociatedRole
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id = mem.member_principal_id
WHERE prin.sid IS NOT NULL
AND prin.sid NOT IN (0x00)
AND prin.is_fixed_role <> 1
AND prin.NAME NOT LIKE '' ## %'''
SELECT dbname
,username
,STUFF((
SELECT ',' + CONVERT(VARCHAR(500), associatedrole)
FROM @DB_USers user2
WHERE user1.DBName = user2.DBName
AND user1.UserName = user2.UserName
FOR XML PATH('')
), 1, 1, '') AS Permissions_user
FROM @DB_USers user1
GROUP BY dbname
,username
ORDER BY DBName
,username
答案 0 :(得分:0)
我认为这就是你想要的。它列出了每个用户及其角色。
SELECT users.name, roles.name
FROM sys.database_role_members roleToUsers JOIN sys.database_principals roles
ON roleToUsers.role_principal_id = roles.principal_id
JOIN sys.database_principals users
ON roleToUsers.member_principal_id = users.principal_id;
这对你有用吗?