Cannot create a CLUSTERED INDEX on a View because

2019-08-05 05:48发布

问题:

I want to create an indexed view that integrates data from several tables, however SQL Server complains with the error message:

Cannot create index on view "MyView". The view contains a self join on "dbo.Companies".

The view definition is something like this (simplified version):

SELECT  T.Field1
      , T.Field2
      , P.CompanyName AS ProviderName
      , C.CompanyName AS CustomerName
      , T3.Field1
FROM dbo.Table1 T 
                  INNER JOIN dbo.Companies P ON T.ProviderId = T2.Id
                  INNER JOIN dbo.Companies C ON T.CustomerId = T2.Id
                  INNER JOIN dbo.Table3 ON T.Id = T3.Id

Is there any workaround for this case? I don't want to split the Companies table in two tables.

Thanks in advance.

回答1:

You won't be able to work around this, the indexed views must conform to certain restrictions enumerated in Creating Indexed Views. Among other things, outer and self joins are not supported (10th restriction from top to bottom). It boils down to the engine ability to be able to update the view index when the base table is updated.

Not knowing exact all the details of your data model, are you sure that an indexed view is necessary and won't the base table indexes suffice?