单独的线程 我得到了一个工作示例,说明如何将我的存储的Proc转换为视图,该视图将客户名称保存在订单映射中,其中订单是逗号分隔的订单列表,包括无订单的null。因此,对于下表,我需要以下内容出现在视图中:

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

我需要索引视图,但是如果视图中的选择查询已应用和/或子查询,则不能这样做。是否可以将此视图转换为索引视图?

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
有帮助吗?

解决方案

您不能将此视图索引。

基本上,您在这里具有汇总功能(伪装为 CROSS APPLY).

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

该属性是需要维护的索引所必需的。

当从基础表中插入,更新或删除新记录时,整个视图无需重新评估:新记录的值只是从汇总值中添加或减去。

另外, COUNT_BIG 也应该是视图的一部分,以跟踪记录的删除(当 0, ,应从视图索引中删除记录)。

其他提示

如果您使用1 = 1的内部连接,它将满足条件,并允许连接。

从x内连接y上选择 * 1 = 1

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top