Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

1 Answer 1

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
add comment

Your Answer

 
discard

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.