开发者

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

开发者 https://www.devze.com 2023-01-31 15:46 出处:网络
I want to create indexed view MyView with such t-sql Select o.Theme_ID as Theme_ID, DATEADD(day, DATEDIFF(day, 0, o.Object_CreationDate), 0) as Objext_CreationDate,

I want to create indexed view MyView with such t-sql

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.

The problem is that table ThemeWorkplace contains several records with same Theme_ID. AND even I use GROUP BY - I get in Object_Count value that

equals: (real Object_Count value) * count(Theme_ID in ThemeWorkplace ).

I can't use DISTINCT word in t-sql, because in this case it is impossible to create index on view.

What is a su开发者_开发百科ggestion 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号