17

我正在寻找一个 select 语句,它将检索我当前连接的所有数据库角色的列表。

我想创建一个视图,它将所有角色返回给客户端软件,以便软件可以根据角色调整其用户界面(例如显示/隐藏菜单条目等)

4

1 回答 1

27

您不应使用已弃用的向后兼容性视图(例如,在此页面中搜索sysusers)。相反,您应该使用sys.database_principalsand sys.database_role_members。请记住,当前连接可能已被授予数据库范围之外的访问权限(例如,如果用户恰好是,这些将返回空结果,sysadmin在这种情况下,他们不需要显式授予角色成员资格或特定权限)。同样对于在角色范围之外显式分配的权限,这将覆盖角色提供的权限,您应该另外检查sys.database_permissions. 这是一个独立的示例,您可以查看(只要您还没有名为的登录名blatfarA或名为 的数据库floob)。

CREATE LOGIN blatfarA WITH PASSWORD = 'foo', CHECK_POLICY = OFF;
GO
CREATE DATABASE floob;
GO
USE floob;
GO
CREATE USER blatfarB FROM LOGIN [blatfarA] WITH DEFAULT_SCHEMA = dbo;
GO
GRANT SELECT, UPDATE ON SCHEMA::dbo TO blatfarB;
DENY INSERT, EXECUTE ON SCHEMA::dbo TO blatfarB;
GO
EXEC sp_addrolemember N'db_datareader', N'blatfarB'
GO

要测试它:

EXECUTE AS LOGIN = N'blatfarA';
GO

DECLARE @login NVARCHAR(256), @user NVARCHAR(256);

SELECT @login = login_name FROM sys.dm_exec_sessions WHERE session_id = @@SPID;

SELECT @user = d.name
  FROM sys.database_principals AS d
  INNER JOIN sys.server_principals AS s
  ON d.sid = s.sid
  WHERE s.name = @login;

SELECT u.name, r.name
  FROM sys.database_role_members AS m
  INNER JOIN sys.database_principals AS r
  ON m.role_principal_id = r.principal_id
  INNER JOIN sys.database_principals AS u
  ON u.principal_id = m.member_principal_id
  WHERE u.name = @user;

SELECT class_desc, major_id, permission_name, state_desc
  FROM sys.database_permissions
  WHERE grantee_principal_id = USER_ID(@user);

GO
REVERT;

结果:

name      name
--------  -------------
blatfarB  db_datareader

class_desc  major_id  permission_name  state_desc
----------  --------  ---------------  ----------
DATABASE    0         CONNECT          GRANT
SCHEMA      1         INSERT           DENY
SCHEMA      1         EXECUTE          DENY
SCHEMA      1         SELECT           GRANT
SCHEMA      1         UPDATE           GRANT

清理:

USE master;
GO
ALTER DATABASE floob SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
DROP DATABASE floob;
GO
DROP LOGIN blatfarA;
GO
于 2013-08-12T15:36:42.303 回答