Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the USER is already created in the database or not in SQL?

Tags:

sql

tsql

Is there is a way that from it I can know if the user(not the login) is already created in the database? I mean the user not the login, since, I know how to check for the login. I need to check for the user that is created inside a specific DB & a role assigned to it.

This is the code for checking for the login:

SELECT name FROM sys.server_principals WHERE name = 'test_user' 

but how about the user? Since I need to create the user and assign a role to it if its not created. Otherwise, I will continue without creating.

Thanks

like image 822
Q8Y Avatar asked Jul 17 '11 07:07

Q8Y


People also ask

How do I find the database user in SQL?

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 do you check if login already exists in SQL Server?

If you need to check if a login exists in SQL Server , you can use query the master. dbo. syslogins for it.

How can I tell if a SQL Server user is connected?

In SQL Server Management Studio, right click on Server, choose "Activity Monitor" from context menu -or- use keyboard shortcut Ctrl + Alt + A .

How can I tell who created a SQL Server user?

SQL Server: Find Users in SQL Server Answer: In SQL Server, there is a system view called sys. database_principals. You can run a query against this system view that returns all of the Users that have been created in SQL Server as well as information about these Users.


1 Answers

How about:

USE (your database you want to check the user's existence in)  SELECT *  FROM sys.database_principals WHERE name = '(your user name to check here)' 

sys.server_principals shows you the logins defined on the server level - sys.database_principals shows you the principals (e.g. user accounts) on a database level.

like image 111
marc_s Avatar answered Oct 11 '22 23:10

marc_s