且构网

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

SQL Server 2008 上的唯一键与唯一索引

更新时间:2022-12-10 16:59:43

唯一约束在幕后实现为唯一索引,因此您如何指定它并不重要.我倾向于简单地实现它:

A unique constraint is implemented behind the scenes as a unique index, so it doesn't really matter how you specify it. I tend to implement it simply as:

ALTER TABLE dbo.foo ADD CONSTRAINT UQ_bar UNIQUE(bar);

有些人会创建唯一索引,例如

Some people create a unique index instead, e.g.

CREATE UNIQUE INDEX IX_UQ_Bar ON dbo.foo(bar);

区别在于意图 - 如果您要创建约束来强制执行唯一性/业务规则,则创建一个约束,如果您这样做是为了帮助查询性能,则创建唯一索引可能更合乎逻辑.同样,在幕后,它是相同的实现,但您实现目标的方式可能有助于记录您的意图.

The difference is in the intent - if you are creating the constraint to enforce uniqueness/business rules, you create a constraint, if you are doing so to assist query performance, it might be more logical to create a unique index. Again, under the covers it's the same implementation, but the road you take to get there may help document your intent.

我认为有多种选择可以同时遵守以前的 Sybase 功能以及遵守 ANSI 标准(即使唯一约束没有 100% 遵守标准,因为它们只允许一个 NULL 值 - 一个唯一的另一方面,索引可以通过在 SQL Server 2008 及更高版本上添加 WHERE 子句(WHERE col IS NOT NULL)来解决此问题.

I think there are multiple options to adhere to both previous Sybase functionality as well as to adhere to the ANSI standard (even though unique constraints don't adhere to the standard 100%, since they only allow one NULL value - a unique index, on the other hand, can work around this by adding a WHERE clause (WHERE col IS NOT NULL) on SQL Server 2008 and greater).