简体   繁体   English

具有与SQL Server 2008 R2中的DISTINCT相同的结果的索引视图和T-sql

[英]Indexed view and T-sql that give same results as DISTINCT in SQL Server 2008 R2

I want to create indexed view MyView with such t-sql 我想用这样的T-SQL创建索引视图MyView

Select 
    o.Theme_ID as Theme_ID,
    DATEADD(day, DATEDIFF(day, 0, o.Object_CreationDate), 0) as Objext_CreationDate,
    Count_BIG(*) as ObjectCount,   o.Object_Tonality from [dbo].Object o
inner join [dbo].Theme t on o.Theme_ID = t.Theme_ID
inner join [dbo].[ThemeWorkplace] tw on t.Theme_ID = tw.Theme_ID
inner join [dbo].Workplace w on w.Workplace_ID = tw.Workplace_ID
 ... where t.Theme_DeletedMark = 0
 AND (w.Workplace_AccessType = 1 OR w.Workplace_AccessType = 8)
 AND Object_DeletedMark = 0 ...
 Group BY o.Theme_ID,o.Object_Tonality, DATEADD(day, DATEDIFF(day, 0, o.Object_CreationDate), 0)

This t-sql works fine and allows to set a clustered index on MyView . 该t-sql可以正常工作,并允许在MyView上设置聚簇索引。

The problem is that table ThemeWorkplace contains several records with same Theme_ID . 问题在于表ThemeWorkplace包含具有相同Theme_ID多个记录。 AND even I use GROUP BY - I get in Object_Count value that 而且甚至我使用GROUP BY我得到的Object_Count
equals: (real Object_Count value) * count( Theme_ID in ThemeWorkplace ). 等于:(实际Object_Count值)* count( Theme_ID中的ThemeWorkplace )。

I can't use DISTINCT word in t-sql, because in this case it is impossible to create index on view. 我不能在t-sql中使用DISTINCT单词,因为在这种情况下,无法在视图上创建索引。

What is a suggestion to get correct results in my view ? 我认为要获得正确的结果有什么建议?

As you've noted, there are significant restrictions on creating an indexed view. 正如您已经指出的,创建索引视图有很多限制。 The techniques that might help you here, such as distinct or a subquery are prohibited. 禁止使用可能在这里对您有所帮助的技术,例如独立查询或子查询。 I think you'll need to sacrifice materializing the view in this particular case. 我认为在这种特殊情况下,您需要牺牲实现视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM