USE AdventureWorks;
GO
--Set the options to support indexed views.
SET NUMERIC_ROUNDABORT OFF;
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT,
QUOTED_IDENTIFIER, ANSI_NULLS ON;
GO
--Create view with schemabinding.
IF OBJECT_ID ('Sales.vOrders', 'view') IS NOT NULL
DROP VIEW Sales.vOrders ;
GO
CREATE VIEW Sales.vOrders
WITH SCHEMABINDING
AS
SELECT SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Revenue,
OrderDate, ProductID, COUNT_BIG(*) AS COUNT
FROM Sales.SalesOrderDetail AS od, Sales.SalesOrderHeader AS o
WHERE od.SalesOrderID = o.SalesOrderID
GROUP BY OrderDate, ProductID;
GO
--Create an index on the view.
CREATE UNIQUE CLUSTERED INDEX IDX_V1
ON Sales.vOrders (OrderDate, ProductID);
GO
Bước 1: Tạo viewTrong Object Explorer, nhấn chuột phải vào mục view chọn New View
Bước 2: Chọn các bảng tham chiếuGiữ Ctrl và click vào các bảng muốn tham chiếu rồi nhấn nút Add
Bước 3: Chọn các trường giữ liệu:
Bước 5: Thiết lập thuộc tính cho view:Nhấn chuột trái vào vùng trống trong khung View DesignMở cửa cửa sổ PropertiesThiết lập thuộc tính Bind To Schema = Yes
Bước 6: Lưu lạiNhấn nút SaveĐặt tên cho view
Bước 7: Tạo unique clustered indexTrong Object Explorer, nhấn chuột phải vào mục Indexes chọn New Index
Bước 8: Thiết lập các thuộc tính để tạo unique clustered index- chọn mục General- Đặt tên- Chọn Index Type là Clustered- Check vào ô Unique- Nhấn nút Add và chọn các trường dữ liệu muốn index
Bước 9: Lưu lại- Nhấn nút OK