Running the T-Sql script below will return a list of essentially all users from all databases in an instance. This is a particularly useful script if you are assessing the back end security matrix for a company. You may want to do thisĀ ahead of GDPR coming into effect to determine if your company is compliant . Data for the following fields are provided.
- ServerName
- DbName
- UserName
- LoginType
- Permission
- StateOf
- AccessLevel
- ObjectName
SET NOCOUNT ON; DECLARE @Database TABLE (DbName SYSNAME); DECLARE @DbName AS SYSNAME; DECLARE @sql AS VARCHAR(MAX); DECLARE @ServerName AS SYSNAME; SET @ServerName = ( SELECT @@SERVERNAME ); IF OBJECT_ID(N'tempdb..#User') IS NOT NULL BEGIN DROP TABLE #User END; CREATE TABLE #User ( ServerName SYSNAME ,DbName SYSNAME ,UserName SYSNAME NULL ,LoginType VARCHAR(255) NULL ,Permission VARCHAR(255) NULL ,StateOf VARCHAR(255) NULL ,AccessLevel VARCHAR(255) NULL ,ObjectName SYSNAME NULL ); SET @DbName = ''; INSERT INTO @Database (DbName) SELECT NAME FROM master.dbo.sysdatabases WHERE NAME <> 'tempdb' ORDER BY NAME ASC; WHILE @DbName IS NOT NULL BEGIN SET @DbName = ( SELECT MIN(DbName) FROM @Database WHERE DbName > @DbName ) /* PUT CODE HERE */ SET @sql = ' INSERT INTO #User ( ServerName ,DbName ,UserName ,LoginType ,Permission ,StateOf ,AccessLevel ,ObjectName ) SELECT ''' + @ServerName + ''' AS ServerName ,''' + @DbName + ''' AS DbName ,princ.name AS UserName ,princ.type_desc AS LoginType ,perm.permission_name AS Permission ,perm.state_desc AS StateOf ,perm.class_desc AS AccessLevel ,object_name(perm.major_id) AS ObjectName FROM ' + QUOTENAME(@DbName) + '.sys.database_principals princ LEFT JOIN ' + QUOTENAME(@DbName) + '.sys.database_permissions perm ON perm.grantee_principal_id = princ.principal_id ' EXEC (@sql) END; SELECT * FROM #User; DROP TABLE #User;
Server name is included in case you’d like to run this script across multiple environments. The results of each server can be combined in an excel file more easily.
DbName and UserName are self explanatory.
LoginType, whether the login is via Windows or SQL Server.
Permission, what actions the user can perform e.g. SELECT, UPDATE etc.
StateOf, whether permission to the object has been granted or denied.
AccessLevel, whether the user has access to the entire database or is restricted to objects etc. though it is good practice that a user should have locked down access. From a GDPR perspective it would be hard to make a case for allowing a user to have access to an entire database instead of a few columns, views or stored procedures.
ObjectName, if the user only has restricted access to specific objects this script will list them.