Checking if a SQL Server login already exists

Brett Rigby picture Brett Rigby · Sep 4, 2009 · Viewed 190.9k times · Source

I need to check if a specific login already exists on the SQL Server, and if it doesn't, then I need to add it.

I have found the following code to actually add the login to the database, but I want to wrap this in an IF statement (somehow) to check if the login exists first.

CREATE LOGIN [myUsername] WITH PASSWORD=N'myPassword', 
DEFAULT_LANGUAGE=[us_english], 
CHECK_EXPIRATION=OFF, 
CHECK_POLICY=OFF 
GO

I understand that I need to interrogate a system database, but not sure where to start!

Answer

Derek Morrison picture Derek Morrison · Dec 22, 2009

Here's a way to do this in SQL Server 2005 and later without using the deprecated syslogins view:

IF NOT EXISTS 
    (SELECT name  
     FROM master.sys.server_principals
     WHERE name = 'LoginName')
BEGIN
    CREATE LOGIN [LoginName] WITH PASSWORD = N'password'
END

The server_principals view is used instead of sql_logins because the latter doesn't list Windows logins.

If you need to check for the existence of a user in a particular database before creating them, then you can do this:

USE your_db_name

IF NOT EXISTS
    (SELECT name
     FROM sys.database_principals
     WHERE name = 'Bob')
BEGIN
    CREATE USER [Bob] FOR LOGIN [Bob] 
END