开发者

Making Column data Unique in SQL Server Management Studio

Let's say I have a database with several columns. There is a primary key, Users. But there is also annother column, Username. When a new Username is entered into the database, I want to check to make sure it is unique. Since there is already a primary key, maybe I need to put a constraint开发者_高级运维 on Username.

I have no idea how to do this. When I right click on the column name and I bring up "Indexes/Keys" I see "Users_Key" for the existing primary key, not "Users". So I have to add something like "Username_Keys"? When I do, I don't see it anywhere in the Object Explorer. But I do see Users_Key under "Keys"?


Is it okay to use a query within SSMS?

Cos then you could do this:

ALTER TABLE tablename
ADD UNIQUE (Username)

where the table is called tablename and the Username column (which you want to be unique) is called Username.

For multiple columns, do it like this:

ALTER TABLE tablename
ADD CONSTRAINT uc_NameofConstraint UNIQUE (column1,column2)

To be honest, it's better to do it the second way, as you may need to drop the constraint later for some reason. Like this:

ALTER TABLE tablename
DROP CONSTRAINT uc_NameofConstraint

Don't forget that a UNIQUE constraint has a size limit (I believe it's around 900 bytes, but not 100% sure), so make sure UserName is not a column type like NVARCHAR(MAX) or it won't let you do it! But you'd be insane to let anybody have a username over 100 characters anyway!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜