user1108948
user1108948

Reputation:

Ensure unique username

Asp.net membership 2.0.

I want to update the username in table aspnet_user, the best way is to update the table directly.

UPDATE aspnet_Users SET UserName = @UserName,LoweredUserName = LOWER( @UserName) 
WHERE UserName = @CurrentUname 

How to ensure it is unique?

Thanks,

UPDATE: If not exist (select UserName from aspnet_Users) Begin UPDATE aspnet_Users SET UserName = @UserName,LoweredUserName = LOWER( @UserName)
WHERE UserName = @CurrentUname
End

HOW TO MODIFY THE CODE ABOVE?

Second Update:

If not exist (select UserName from aspnet_Users WHERE UserName = @CurrentUname)
Begin 
  UPDATE aspnet_Users SET UserName = @UserName,LoweredUserName = LOWER( @UserName)
WHERE UserName = @CurrentUname
End
SELECT 1;
else
select 0;

Upvotes: 0

Views: 1923

Answers (3)

Pankaj
Pankaj

Reputation: 10105

In addition to @Icarus and @Pete M Replies. These are already Good/Trusted suggestion.

Alternative is, Can you use TransactionScope ?

Pseudo Code

using (TransactionScope scope = new TransactionScope())
{
    UPDATE aspnet_Users 
    SET    UserName = @UserName,
           LoweredUserName = LOWER( @UserName) 
    WHERE  UserName = @CurrentUname

    if((select count(userName) 
        From   aspnet_Users
        Where  userName = @CurrentUname) = 1)
    Begin
         scope.Complete
    End
}

The above approach keeps the independent session of the request under Transaction and keep it isolated from other request made by other users.

Upvotes: 1

Pete M
Pete M

Reputation: 2048

Place a unique constraint on the column in the database. Then either check for an existing username before attempting the update, or catch the exception and handle it accordingly.

Upvotes: 3

Icarus
Icarus

Reputation: 63966

Create a unique index on the username column.

Something like:

CREATE UNIQUE INDEX index_username
ON aspnet_Users (UserName)

Upvotes: 4

Related Questions