TSQL了解数据库角色成员

时间:2010-01-27 20:12:19

标签: sql-server sql-server-2005 tsql sql-server-2000

我正在使用SQL 2000和SQL 2005。

我想知道哪些登录对哪些数据库具有db_owner或db_accessadmin权限。

我可以点击每个数据库中的用户或数据库角色来查看。 这可以使用TSQL以更简单的方式完成吗?

提前致谢

2 个答案:

答案 0 :(得分:18)

对于SQL 2000,仍然适用于SQL 2005

SELECT
    USER_NAME(memberuid), USER_NAME(groupuid)
FROM
    sys.sysmembers
WHERE
    USER_NAME(groupuid) IN ('db_owner', 'db_accessadmin')

答案 1 :(得分:3)

它很草率,可能有更好的方法,但如果这是一次性的话,这应该完成:

DECLARE
    @db_name SYSNAME,
    @sql VARCHAR(1000)

DECLARE db_cursor CURSOR FOR SELECT Name FROM sys.databases
OPEN db_cursor

FETCH NEXT FROM db_cursor INTO @db_name

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SET @sql =
        'SELECT
            ''' + @db_name + ''' AS [Database],
            USER_NAME(role_principal_id) AS [Role],
            USER_NAME(member_principal_id) AS [User]
        FROM
            ' + @db_name + '.sys.database_role_members
        WHERE
            USER_NAME(role_principal_id) IN (''db_owner'', ''db_accessadmin'')'
    EXEC(@sql)

    FETCH NEXT FROM db_cursor INTO @db_name
END

CLOSE db_cursor
DEALLOCATE db_cursor

SQL 2000版本应为:

DECLARE
    @db_name SYSNAME,
    @sql VARCHAR(1000)

DECLARE db_cursor CURSOR FOR SELECT Name FROM master..sysdatabases
OPEN db_cursor

FETCH NEXT FROM db_cursor INTO @db_name

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SET @sql =
        'SELECT
            ''' + @db_name + ''' AS [Database],
            USER_NAME(memberuid) AS [Role],
            USER_NAME(groupuid) AS [User]
        FROM
            sysmembers
        WHERE
            USER_NAME(groupuid) IN (''db_owner'', ''db_accessadmin'')'
    EXEC(@sql)

    FETCH NEXT FROM db_cursor INTO @db_name
END

CLOSE db_cursor
DEALLOCATE db_cursor