Sql-server – The login already has an account under a different user name

loginsSecuritysql server

When I execute this SQL:

USE ASPState
GO
IF NOT EXISTS(SELECT * FROM sys.sysusers WHERE NAME = 'R2Server\AAOUser')
CREATE USER [R2Server\AAOUser] FOR LOGIN [R2Server\AAOUser];
GO

I get the following error:

The login already has an account under a different user name.

How do I know what this different user name is for my login account?

Best Answer

This means that the login [R2Server\AAOUser] is already mapped to a user in that database. Or, in other words, another database user is using this login. You can see what database user is using your login with the following query:

use YourDB
go
SELECT su.name as DatabaseUser
FROM sys.sysusers su
join sys.syslogins sl on sl.sid = su.sid
where sl.name = 'test' -- login

PS: a version of the script that doesn't use the compatibility views:

Select sp.name as LoginName, sp.type_desc as LoginType,
    dp.name as DBUser, dp.type_desc as UserType
from sys.server_principals sp
join sys.database_principals dp on dp.sid = sp.sid
where sp.name = 'test' -- your login