How to get the list of all database users

前端 未结 6 1943
感情败类
感情败类 2021-01-30 06:40

I am going to get the list of all users, including Windows users and \'sa\', who have access to a particular database in MS SQL Server. Basically, I would like the list to look

6条回答
  •  情深已故
    2021-01-30 07:05

    Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.

    Run Sql Profiler. Attach it to your database of course.

    Then right click in the GUI (in SSMS) and click "Refresh".
    And then go see what Profiler "catches".

    I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".

    Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.

    But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.

    SELECT
    u.name AS [Name],
    'Server[@Name=' + quotename(CAST(
            serverproperty(N'Servername')
           AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
    u.create_date AS [CreateDate],
    u.principal_id AS [ID],
    CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
    FROM
    sys.database_principals AS u
    LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
    WHERE
    (u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
    ORDER BY
    [Name] ASC
    

提交回复
热议问题