Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a script that creates a user associated with a login for SQL Server 2005. It does this immediately after creating the database and the login. One user of the script reported the following error:

The login already has an account under a different user name

Any idea how this might happen, and how I could modify the script to handle it?

share|improve this question
up vote 0 down vote accepted

In the section where you create the usern where 'UserName' is your database user name and 'LoginName' is the server login name. (they are often the same) The following code uses the IF NOT EXISTS to check the user, if it already exists the create won't run. Note: this shouls be run in the context of the user database, not master.

IF  NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'UserName')
CREATE USER [UserName] FOR LOGIN [LoginName]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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