Unique constraint on table column

房东的猫 提交于 2019-12-14 02:21:07

问题


I'm having a table (an existing table with data in it) and that table has a column UserName. I want this UserName to be unique. So I add a constraint like this:

ALTER TABLE Users 
ADD CONSTRAINT [IX_UniqueUserUserName] UNIQUE NONCLUSTERED ([UserName])

Now I keep getting the Error that duplicate users exist in this table. But I have checked the database using the following query:

SELECT COUNT(UserId) as NumberOfUsers, UserName 
FROM Users 
GROUP BY UserName, UserId 
ORDER BY UserName

This results in a list of users all having 1 as a NumberOfUsers. So no duplicates there. But when I'm checking the username he fails I see the following result:

beluga
béluga

So apperently he fails to compare an "e" and "é" or "è" ... It's like he ignores these, is there any way that sql doesn't ignore these accents when adding the unique key contraint.

SOLUTION:

THX to you guys I've found the solution. This fixed the problem:

ALTER TABLE Users 
ALTER COLUMN UserName nvarchar(250) COLLATE SQL_Latin1_General_CP1_CI_AS

回答1:


The collation you are using most likely ignores case and accents when comparing. You'll need to change the collation.

  • Latin1_General_CI_AI Ignores case and accents
  • Latin1_General_CI_AS will not ignore accents

List of SQL server collation names here.




回答2:


Your query groups by UserID too - you don't want to be doing that.

Use:

SELECT COUNT(*) as NumberOfUsers, UserName 
    FROM Users 
    GROUP BY UserName 
    ORDER BY UserName

Your query would only show up users with the same name and same user ID. Or, maybe, order the data by COUNT(*) so the last row that shows up is most likely the troublemaker?

You could also have problems with collation as others have suggested, but normally, GROUP BY would be self-consistent.




回答3:


Presumably UserId is your primary key. Since it's part of what you are grouping by, you are guaranteed to get a single row per group. Take the "userId" column out of your group by.




回答4:


As Andrew Barrett says, the default collation in MySQL doesn not recognize accents correctly.

Change the collation of your fields to UTF8_unicode_ci and it should see accents properly.

ci means case insensitive, and you can use a different collation if case is important.

You can create a new table with the new collation, then copy * from the existing table into the new one.




回答5:


Also note that you can also create just the table you are interested in the relevent collation (instead of server wide) .So you could also do something like :

CREATE TABLE Users (c1 varchar (10), .., COLLATE Latin1_General_CI_AS NULL )


来源:https://stackoverflow.com/questions/609676/unique-constraint-on-table-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!