SQL Security queries

Well, I'm on a security kick this morning. Another request came in from a SOX company asking for a query to tell what rights (specifically what ADMIN rights) are assigned to SQL users. There are two queries below that return this info, one for the SERVER SYSADMIN role and one for the DATABASE DB_OWNER role

 

USE master
GO
--get a list of SERVER users, and tell if they're SYSADMIN 
SELECT  p.name AS [loginname] ,
        p.type ,
        p.type_desc ,
        p.is_disabled,
        s.sysadmin ,
        CONVERT(VARCHAR(10),p.create_date ,101) AS [created],
        CONVERT(VARCHAR(10),p.modify_date , 101) AS [update]
FROM    sys.server_principals p
        JOIN sys.syslogins s ON p.sid = s.sid
WHERE   p.type_desc IN ('SQL_LOGIN', 'WINDOWS_LOGIN', 'WINDOWS_GROUP')
        -- Logins that are not process logins
        AND p.name NOT LIKE '##%'
GO
 
--for each DATABASE (returns multiple result sets)
--get the name of each user in the db_owner role
exec sp_msForEachDb ' use [?] 
select db_name() as [database_name], r.[nameas [role], p.[nameas [member] from  
    sys.database_role_members m 
join 
    sys.database_principals r on m.role_principal_id = r.principal_id 
join 
    sys.database_principals p on m.member_principal_id = p.principal_id 
where 
    r.name = ''db_owner'''

 

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences