在一个单独的线程上,我得到了一个关于如何将存储的过程转换为视图的工作示例,该视图将保存客户名称到订单的映射,其中订单是以逗号分隔的订单列表,包括 NULL 表示没有订单。所以对于下表,我需要以下内容出现在视图中:
Name Orders
'John' New Hat, New Book, New Phone
'Marry' NULL
我需要为视图编制索引,但如果视图中的 SELECT 查询具有 APPLY 和/或子查询,则不能这样做。是否可以将此视图转换为索引视图?
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