在 SQL Server Management Studio 中使列数据唯一
假设我有一个包含多个列的数据库。 有一个主键,Users。 但还有另一列,用户名。 当新的用户名输入数据库时,我想检查以确保它是唯一的。由于已经有主键,也许我需要对用户名施加约束。
我不知道该怎么做。当我右键单击列名称并调出“索引/键”时,我会看到现有主键的“Users_Key”,而不是“Users”。所以我必须添加类似“Username_Keys”的内容?当我这样做时,我在对象资源管理器中看不到它。但我确实在“Keys”下看到了Users_Key?
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以在 SSMS 中使用查询吗?
那么你可以这样做:
表名为
tablename
,用户名列(你希望它是唯一的)名为Username
。对于多列,这样做:
说实话,最好采用第二种方式,因为稍后您可能需要出于某种原因删除约束。像这样:
不要忘记
UNIQUE
约束有大小限制(我相信它大约是 900 字节,但不是 100% 确定),所以请确保 UserName 不是像这样的列类型NVARCHAR(MAX)
否则它不会让你这样做!但无论如何,如果让任何人拥有超过 100 个字符的用户名,那就太疯狂了!Is it okay to use a query within SSMS?
Cos then you could do this:
where the table is called
tablename
and the Username column (which you want to be unique) is calledUsername
.For multiple columns, do it like this:
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:
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 likeNVARCHAR(MAX)
or it won't let you do it! But you'd be insane to let anybody have a username over 100 characters anyway!