別のスレッドで、ストアドプロシージャをビューに変換する方法の実例を取得しました。これは、顧客名を注文マッピングに保持します。注文は、注文がない場合の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