T-SQL:如何创建区分大小写的唯一键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/485359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:54:24  来源:igfitidea点击:

T-SQL: How do I create a unique key that is case sensitive?

sqlsql-servertsqlconstraints

提问by Seibar

How do I create a unique constraint on a varcharfield that is case sensitive (SQL Server 2005)?

如何在varchar区分大小写的字段 (SQL Server 2005)上创建唯一约束?

Currently my constraint looks like this:

目前我的约束看起来像这样:

alter table MyTable
add constraint UK_MyTable_MyUniqueKey unique nonclustered (MyCol)

When I try to insert the following two values, I get a "Violation of UNIQUE KEY constraint..." error.

当我尝试插入以下两个值时,出现“违反唯一键约束...”错误。

insert into MyTable (MyCol) values ('ABC')
insert into MyTable (MyCol) values ('abc') --causes a violation of UNIQUE KEY constraint 'UK_MyTable_MyUnqiueKey'

I would like the two differently-cased values to be handled as unqiue. I imagine it will involve the following code, but I do not know how it changes my add constraintsyntax.

我希望将两个不同大小写的值作为 unqiue 处理。我想它会涉及以下代码,但我不知道它如何改变我的add constraint语法。

COLLATE SQL_Latin1_General_CP1_CS_AS

回答by Jason Punyon

This will change the column to be case sensitive. I don't think there's any change to your constraint...

这会将列更改为区分大小写。我不认为你的约束有任何改变......

ALTER TABLE mytable 
ALTER COLUMN mycolumn VARCHAR(10) 
COLLATE SQL_Latin1_General_CP1_CS_AS

Any selects or joins on this column will become case sensitive as a result of this operation.

由于此操作,此列上的任何选择或连接都将区分大小写。

回答by dkretz

You can only set the case-sensitivity of the data in the database (smallest granularity of column). You can't set case-sensitivity of an index - that would be equivalent to being able to index on an expression, which is possible in some databases but not Sql Server.

您只能设置数据库中数据的大小写敏感度(列的最小粒度)。您不能设置索引的区分大小写 - 这相当于能够对表达式进行索引,这在某些数据库中是可能的,但在 Sql Server 中是可能的。