过滤非聚集索引异常行为

时间:2011-08-12 20:24:13

标签: sql-server sql-server-2008 indexing non-clustered-index

我有一个表在某些列上创建了一些过滤的非群集,例如:

CREATE UNIQUE NONCLUSTERED INDEX [IX_Sh_Esh] ON [dbo].[My_Tbl] 
(
    [City_Code] ASC,
[Sh_Esh] ASC
)
WHERE ([Sh_Bod]=(0) AND [Noe_Fa]=(0))
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,            IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_Kho] ON [dbo].[My_Tbl] 
(
[City_Code] ASC,
[Kho] ASC
)
WHERE ([Sh_Bod]=(0) AND [Sh_Esh]=(0) AND [Noe_Fa]=(1))
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,     IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

我在我的表上创建了这个索引而没有错误,但是当我想添加一个新列时,我收到了这个错误:

'My_Tbl' table
- Unable to create index 'IX_Sh_Esh'.  
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'My_Tbl' and the index name 'IX_Sh_Esh'. The duplicate key value is (3, 0).

声明已经终止。

我的表数据是:

enter image description here

根据第一个索引,因为第1行和第4行不满足cluase不应该在其上创建索引。为什么我得到上述错误?

感谢

编辑1)

有趣点。如果我删除该索引并添加列然后重新创建该索引,则索引创建时没有错误.STRANGE !!!!

1 个答案:

答案 0 :(得分:1)

您可以删除索引然后添加数据,然后重新创建索引的原因是因为创建索引不会检查现有数据,只检查您尝试插入/更新的数据。

您没有收到错误,因为它是一个过滤的索引,您正在获取它,因为它是一个唯一索引,并且您尝试将重复值添加到唯一索引所在的表列中。这是他们的好消息!如果您需要重复数据,请不要使索引唯一。