如何在SQL Server中使用NOT IN创建过滤索引

时间:2018-12-12 18:16:50

标签: sql-server tsql indexing

我想创建UNIQUE NONCLUSTERED INDEX,它限制了某些列的特定记录,我正在使用NOT IN对其进行过滤,但由于NOT IN而出现了错误。有什么替代方法?

CREATE UNIQUE NONCLUSTERED INDEX 
[UN_Student] ON [dbo].[Student]
(
[School_Cd] ASC,
[Class_Id] ASC,
[Enroll_Dt] ASC,
[Email_Id] ASC
)
WHERE ([School_Cd]='EM' AND [Class_Id] NOT IN (1,2,3))
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)

2 个答案:

答案 0 :(得分:3)

过滤的索引不能使用NOT IN。您可以改用多个AND运算符。布伦特·奥扎尔(Brent Ozar)的一篇很好的文章here关于过滤索引允许和不允许的内容。

CREATE UNIQUE NONCLUSTERED INDEX 
[UN_Student] ON [dbo].[Student]
(
[School_Cd] ASC,
[Class_Id] ASC,
[Enroll_Dt] ASC,
[Email_Id] ASC
)
WHERE ([School_Cd]='EM' AND [Class_Id] <> 1 AND [Class_Id] <> 2 AND [Class_Id] <> 3)
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)

答案 1 :(得分:0)

x