SQL 服务器物化视图(索引视图)错误

SQL Server Materialized View (Indexed View) error

我正在尝试使用 Microsoft SQL Server Management Studio 14.0.17285.0 创建实体化视图。以下是我最终实现相同目标的脚本。

我的计划是创建一个视图并在其上创建一个索引。

use data_warehouse;

--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 products_yearly_v2
WITH SCHEMABINDING 
AS
    SELECT  
        p.product_id AS product_id, 
        p.product_description AS product_name,
        d.order_year AS order_year,  
        SUM(s.order_total) AS sal_by_dept
    FROM   
        [data_warehouse].[dbo].orders_fact AS s
    INNER JOIN 
        [data_warehouse].[dbo].time_dimension AS d ON s.time_id = d.order_date
    INNER JOIN 
        [data_warehouse].[dbo].product_dimension AS p ON s.product_id = p.product_id
    GROUP BY 
        d.order_year, p.product_id, p.product_description;

CREATE UNIQUE CLUSTERED INDEX IDX_V1   
    ON products_yearly_v1 (order_year, product_id);

我收到这个错误:

Msg 156, Level 15, State 1, Procedure products_yearly_v2, Line 12 [Batch Start Line 7]
Incorrect syntax near the keyword 'CREATE'

更新 添加 COUNT_BIG(*) 以创建索引。

SELECT  COUNT_BIG(*) as count_big, p.product_id as product_id, d.order_year as order_year,  sum(s.order_total) AS sal_by_dept ....

已从 GROUP BY

中删除 product_description
GROUP BY d.order_year,p.product_id;

重新添加,

USE data_warehouse

您需要使用由两部分组成的名称:

SCHEMABINDING

Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. When you use SCHEMABINDING, the select_statement must include the two-part names (schema.object) of tables, views, or user-defined functions that are referenced. All referenced objects must be in the same database.

USE data_warehouse
GO

CREATE VIEW dbo.products_yearly_v2
WITH SCHEMABINDING 
AS 
SELECT  
    p.product_id AS product_id, 
    p.product_description AS product_name,
    d.order_year AS order_year,  
    SUM(s.order_total) AS sal_by_dept
FROM [dbo].orders_fact AS s
JOIN [dbo].time_dimension AS d ON s.time_id = d.order_date
JOIN [dbo].product_dimension AS p ON s.product_id = p.product_id
GROUP BY d.order_year, p.product_id, p.product_description;
GO

-- index on products_yearly_v2 not products_yearly_v1
CREATE UNIQUE CLUSTERED INDEX IDX_V2
   ON dbo.products_yearly_v2 (order_year, product_id);