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?
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.
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.
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?
EXEC sp_helpuser
or
SELECT * FROM sysusers
Both of these select all the users of the current database (not the server).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With