41

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

5 Answers 5

73

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.

1
  • @marc_s: I assumed that the user iN CREATE USER may not match the login in CREATE LOGIN. eg CREATE USER marcs FROM LOGIN gbn
    – gbn
    Jul 17, 2011 at 9:23
14

This will tell you the matching user name for a given login name

USE MyDB
SELECT
    sp.name AS ServerLoginName,
    dp.name AS DBUserName
FROM
    sys.server_principals sp
    LEFT JOIN
    sys.database_principals dp ON sp.sid = dp.sid
WHERE
    sp.name = 'MyLogin'
2
  • This is the more correct answer. The SQL Login might be mapped to a database User with a different name. Sep 23, 2014 at 1:53
  • @themilkyninja, You may have to apply both checks (that one and marc_s's one). If you're going to create a user with specific name, then you have to check that the user name is available (by running the marc_s's check). In addition, due to 1-to-1 link between login and user you must check that no user is associated with the login (by running the gbn's check).
    – Alex Klaus
    May 10, 2017 at 4:10
8
use SomeDatabase
go

/* built-in system function */
select database_principal_id('UserNameHere')

/* check if exists and drop */
if database_principal_id('UserNameHere') is not null
    drop user 'UserNameHere'
go
1
  • Welcome to Stackoverflow. Can you please elaborate on your answer for future users to better understand your response.
    – Sim
    Oct 21, 2016 at 12:36
3

If you've found sys.server_principals, I'm surprised you haven't found sys.database_principals. You can join the views based on the sid column.

0
3

You might care for this method as well...

IF DATABASE_PRINCIPAL_ID('domain\lanid') IS NULL
BEGIN
    CREATE USER [domain\lanid] FOR LOGIN [domain\lanid] WITH DEFAULT_SCHEMA=[dbo]
    EXEC sp_addrolemember N'db_ApplicationUserRole', N'domain\lanid'
END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.