且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2008 区分大小写的唯一列

更新时间:2022-12-12 11:12:15

唯一性可以通过唯一性约束来强制执行.

The uniqueness can be enforced with a unique constraint.

唯一索引是否区分大小写由服务器(或表)的排序规则定义.

Whether or not the unique index is case-sensitive is defined by the server's (or the table's) collation.

您可以使用此查询获取数据库的当前排序规则:

You can get the current collation of your database with this query:

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

你应该得到类似的东西:

and you should get something like:

SQLCollation
————————————
SQL_Latin1_General_CP1_CI_AS

这里,排序规则末尾的CI_AS"表示:CI = Case Insensitive,AS = Accentsensitive.

Here, the "CI_AS" at the end of the collation means: CI = Case Insensitive, AS = Accent sensitive.

这可以更改为您需要的任何内容.如果您的数据库和/或表确实有区分大小写的排序规则,我希望您的索引的唯一性也区分大小写,例如您的 abcdefABCDEF 应该都可以作为唯一字符串接受.

This can be changed to whatever you need it to be. If your database and/or table does have a case-sensitive collation, I would expect that the uniqueness of your index will be case-sensitive as well, e.g. your abcdef and ABCDEF should be both acceptable as unique strings.

马克

更新:

我刚刚尝试过这个(SQL Server 2008 开发人员版 x64) - 对我有用(我的数据库通常使用Latin1_General_CI_AS 排序规则,但我甚至可以为每个表/每个 VARCHAR 列定义一个不同的排序规则):

I just tried this (SQL Server 2008 Developer Edition x64) - works for me (my database is generally using the "Latin1_General_CI_AS collation, but I can define a different one per table / per VARCHAR column even):

CREATE TABLE TestUnique
    (string VARCHAR(50) COLLATE SQL_Latin1_General_Cp1_CS_AS)

CREATE UNIQUE INDEX UIX_Test ON dbo.TestUnique(string)

INSERT INTO dbo.TestUnique(string) VALUES ('abc')
INSERT INTO dbo.TestUnique(string) VALUES ('ABC')

SELECT * FROM dbo.TestUnique

然后我回来:

string
ABC
abc

并且没有关于违反唯一索引的错误.

and no error about the unique index being violated.