Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of all database users

Tags:

sql-server

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 like as what is shown in SQL Server Management Studio (i.e. the list that is shown when you expand [databse] -> Security -> Users) with one important exception: I do not want to see the 'dbo' in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the 'dbo', 'sa' must be included in the list instead of 'dbo'. Another note not to be missed is, the list in the SQL Server Management Studio normally shows Windows users in addition to SQL users, And I would like those users to be included as well.

So far, I have been able to come up with the following query:

SELECT * FROM sys.database_principals where (type='S' or type = 'U') 

This query is almost right but the problem is it doesn't satisfy the 'dbo' condition.

How can I change this query or should I use another one?

like image 674
RGO Avatar asked Sep 18 '13 08:09

RGO


People also ask

How do I get a list of all users in a SQL Server database?

First, move to “Object Explorer” and expand the database that you want. Next, under the database, expand the “Security” directory. Now, under Security, expand the “Users” option. This will display a list that contains all the users created in that database.

How many users are connected to MySQL server database?

In SQL Server Management Studio, right click on Server, choose "Activity Monitor" from context menu -or- use keyboard shortcut Ctrl + Alt + A . Good option, but it requires more priviledges than DB_NAME(dbid) extraction from sys. sysprocesses.


2 Answers

For the SQL Server Owner, you should be able to use:

select suser_sname(owner_sid) as 'Owner', state_desc, * from sys.databases 

For a list of SQL Users:

select * from master.sys.server_principals 

Ref. SQL Server Tip: How to find the owner of a database through T-SQL

How do you test for the existence of a user in SQL Server?

like image 129
Leptonator Avatar answered Oct 16 '22 22:10

Leptonator


EXEC sp_helpuser 

or

SELECT * FROM sysusers 

Both of these select all the users of the current database (not the server).

like image 39
Vedran Avatar answered Oct 16 '22 20:10

Vedran