Sql-server – SQL Script fails with error: The login already has an account under a different user name

sql serversql-server-2005

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?

Best Answer

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]