Assuming you're at least in SQL 2005 ...
The corresponding metadata is stored in sys.database_permissions for database repositories and sys.server_permissions for server-level security. You get a list of database participants (users and roles) from sys.database_principals , server managers (logins of server roles) from sys.server_principals .
This will give you a list of explicit permissions, but you also need to consider implicit permissions that are not declared. Some groups have implicit permission. To complicate matters, you also need to deal with members of Windows groups that are not declared in any SQL view, but are considered when performing access checks. Finally, the access rules are quite complex: a principal may have privilege through an explicit GRANT, through membership in a group that granted privilege, but any DENY exceeds all GRANTS, and this should be taken into account, with the exception of ensuring security ownership that exceeds any DENY . Icing on the cake is a member of sysadmin, which surpasses all privileged rules: sysadmin has all privileges by definition.
You can check any privilege on any one accessible to the majority of participants by impersonating the principal with EXECUTE AS and checking the output of fn_my_permissions in the desired state.
source share