可以在系统表上创建索引视图吗?

Can an indexed view be created on system tables?

为什么不能用 sys. 个表创建索引视图?

我不想每次查询这个视图时都写order by,所以我想在我想要排序的字段上创建一个聚集索引。

这是观点:

ALTER VIEW [dbo].[sysVW_Row_Groups]
--WITH SCHEMABINDING
AS
SELECT 
    OBJECT_NAME(rg.OBJECT_ID) as table_name
    ,i.name as index_name
    --,i.type_desc as index_type_desc

    ,rg.partition_number
    ,p.rows as rows_per_partition_number
    --,p.data_compression_desc as data_compresion_partition
    ,row_group_id
    ,state_description
    ,total_rows as total_rows_row_group
    ,convert(decimal(10,2),(total_rows*1.0/POWER(2,20))*100) as full_row_groups
    --,size_in_bytes
    ,convert(decimal(10,2),(size_in_bytes*1.0)/POWER(2,20)) as size_in_Mbytes 
    ,convert(decimal(10,2),(total_rows*1.0/p.rows)*100) as partition_percentage_rows

    ,deleted_rows
    ,i.compression_delay

    ,ps.name as partition_scheme_name
    --,ps.type_desc as partition_scheme_type_desc

    ,pf.name as partition_function_name
    --,pf.type_desc as partition_function_type_desc
    ,pf.boundary_value_on_right
    ,pf.fanout as number_of_resulting_partitions

FROM SYS.COLUMN_STORE_ROW_GROUPS rg
    inner join sys.partitions p ON rg.partition_number = p.partition_number and object_name(rg.object_id) = object_name(p.object_id) 
            and data_compression_desc = 'COLUMNSTORE' --Focused on in columnstore indexes
    inner join sys.indexes i ON OBJECT_NAME(rg.OBJECT_ID) = OBJECT_NAME(i.OBJECT_ID) 
    inner join sys.partition_schemes ps ON i.data_space_id = ps.data_space_id
    inner join sys.partition_functions pf ON ps.function_id = pf.function_id

我知道这对列存储索引帮助不大,但无论如何...

我收到以下错误消息:

Msg 2720, Level 16, State 1, Procedure sysVW_Row_Groups, Line 10 [Batch Start Line 6]
Cannot schema bind view 'dbo.sysVW_Row_Groups' because it references system object 'SYS.COLUMN_STORE_ROW_GROUPS'.

Select * from indexed_view 不保证查询返回的顺序。 (正如评论所暗示的那样)。所以,请不要假设那样,否则您的应用程序会崩溃。

至于 "why can't you create an indexed view on system tables?" 有几个原因。

  1. 您可以在索引视图上创建约束,这会导致某些系统 DDL 命令失败(您不希望普通用户能够这样做)。
  2. 系统表实际上是视图本身。有不同的基础表,它们不会直接公开(尽管您可以在 showplan 中看到它们)。所以,我们不允许您绑定到内部表。虽然不常见,但 SQL 有时会以可能破坏之前创建的任何索引视图的方式更改这些视图(在主要版本升级时)
  3. 最后,有一个非常不同的代码路径来实现如何更新系统表(视图)。它没有使用正常的更新语句。有很多用于锁、闩锁、维护系统缓存等的特殊逻辑。因此,维护索引视图的逻辑不适用于这些对象。 [这一切都是很久以前以 performance/scale 的名义完成的]