代码之家  ›  专栏  ›  技术社区  ›  kateroh

如何重写交叉应用到内部联接以使视图索引

  •  4
  • kateroh  · 技术社区  · 15 年前

    separate thread

    Name     Orders
    'John'   New Hat, New Book, New Phone
    'Marry'  NULL
    

    我需要为视图编制索引,但如果视图中的SELECT查询已应用和/或子查询,则无法执行此操作。是否可以将此视图转换为索引视图?

    create table Customers (CustomerId int, CustomerName VARCHAR(100))
    create table Orders    (CustomerId int, OrderName VARCHAR(100))
    
    insert into Customers  (CustomerId, CustomerName) select 1, 'John' union all select 2, 'Marry'
    insert into Orders     (CustomerId, OrderName)    select 1, 'New Hat' union all select 1, 'New Book' union all select 1, 'New Phone'
    go
    
    create view OrderView as 
    select c.CustomerName, x.OrderNames        
    from Customers c            
    cross apply (select stuff((select ',' + OrderName from Orders o 
          where o.CustomerId = c.CustomerId for xml path('')),1,1,'') 
          as OrderNames) x
    go
    
    2 回复  |  直到 8 年前
        1
  •  11
  •   Quassnoi    15 年前

    无法将此视图编入索引。

    基本上,这里有一个聚合函数(伪装成 CROSS APPLY ).

    索引视图中唯一允许的聚合函数是 COUNT_BIG SUM ,因为它们分布在加法和减法集合上,即 SUM(a UNION ALL b) = SUM(a) + SUM(b) , SUM(a EXCEPT ALL b) = SUM(a) - SUM(b)

    此属性是索引可维护所必需的。

    此外,a 大伯爵 也应该是视图的一部分,以跟踪记录的删除(当它变成 0 ,应从视图索引中删除一条记录)。

        2
  •  -1
  •   David Rosskopf    6 年前

    选择* 从x