列忽略创建唯一索引

时间:2014-02-21 19:18:47

标签: sql-server

给出一个观点

CREATE VIEW MyView WITH SCHEMABINDING AS 
SELECT  A, B, Year, t1.FKId, C, D, COUNT_BIG(*) as Cnt, SUM(W) As Wgt
FROM [dbo].[T1] t1
INNER JOIN [dbo].T2 t2 ON t1.FKId = t2.Id
INNER JOIN [dbo].T3 t3 ON t1.FKId = t3.FKId AND t1.FKId = t3.FKId
GROUP BY A, B, Year, t1.FKId, C, D

当我尝试将其作为索引视图时

CREATE UNIQUE CLUSTERED INDEX IX_CLU_My
ON MyView (FKId, A, B, Year, C, D)

SQL Server抱怨重复键,但错误消息只考虑指定的6列中的5列:

  

CREATE UNIQUE INDEX语句终止,因为找到了对象名称“dbo.MyView”和索引名称“IX_CLU_My”的重复键。重复键值为(934,1,6,2014,1)。

视图中与前4个键对应的实际数据是:

FKId   A  B  Year  C  D
934    1  6  2014  1  5
934    1  6  2014  1  15
934    1  6  2014  2  5
934    1  6  2014  3  5

考虑前5列,错误消息是正确的。为什么不考虑第6列的唯一性?

1 个答案:

答案 0 :(得分:1)

如果您可以添加HAVING子句并且没有记录返回,那么我将帮助您进一步解决此问题。

SELECT  A, B, Year, t1.FKId, C, D, COUNT_BIG(*) as Cnt
FROM [dbo].[T1] t1
INNER JOIN [dbo].T2 t2 ON t1.FKId = t2.Id
INNER JOIN [dbo].T3 t3 ON t1.FKId = t3.FKId AND t1.FKId = t3.FKId
GROUP BY A, B, Year, t1.FKId, C, D
HAVING Count(*) > 1