Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
可能重复: 在 SQL Server 中实现允许多个 NULL 值的唯一约束的正确方法
我的表中有一个列,其中所有值必须是唯一的或 NULL。
我尝试为该列向表中添加唯一键,但这似乎意味着我只能有 1 个 NULL 值?
如何设置约束以使所有值都是唯一的,除非它们为 NULL?
SQL Server 2008 有过滤索引允许这样做,但它们在 2005 年不可用。在 SQL Server 2005 中,您可以创建一个带有定义的索引视图
CREATE VIEW dbo.Foo WITH SCHEMABINDING AS SELECT bar FROM dbo.baz WHERE bar IS NOT NULL
然后在其上创建一个唯一的聚集索引。
CREATE UNIQUE CLUSTERED INDEX ix ON dbo.Foo(bar)