Search code examples
sql-serversql-server-2005indexed-view

SQL Server Indexed View Error


I realize this is a very contrived example, but I've simplified the full version down to the following which demonstrates the problem:

CREATE VIEW model.Appointments_Partition1
WITH SCHEMABINDING AS
  SELECT CONVERT(varchar(15), AppointmentId) as Id, 
         ap.AppTypeId as AppointmentTypeId, 
         ap.Duration as DurationMinutes, 
         ap.AppointmentId as EncounterId, 
         COUNT_BIG(*) as __count_big
    FROM dbo.Appointments ap 
    JOIN dbo.PracticeCodeTable pct ON SUBSTRING(pct.Code, 1, 1) = ap.ScheduleStatus 
                                  AND pct.ReferenceType = 'AppointmentStatus' 
   WHERE ap.AppTime > 0
GROUP BY CONVERT(varchar(15), AppointmentId), ap.AppTypeId, ap.Duration, ap.AppointmentId

CREATE UNIQUE CLUSTERED INDEX [IX_Appointments_Partition1_Id]
ON model.Appointments_Partition1 ([Id]);

I get:

Msg 8668, Level 16, State 0, Line 12
Cannot create the clustered index 'IX_Appointments_Partition1_Id' on view 'PracticeRepository.model.Appointments_Partition1' because the select list of the view contains an expression on result of aggregate function or grouping column. Consider removing expression on result of aggregate function or grouping column from select list.

I'm including count_big...so why is the group by a problem?....and how can I resolve the error?


Solution

  • Here is the same error message with some boolean logic applied to it:

    Cannot create the clustered index '...' on view '...' because the select list of the view contains an expression on a grouping column. Consider removing expression on a grouping column from the select list.

    You need to remove the CONVERT in CONVERT(varchar(15), AppointmentId)