CREATE INDEX (Transact-SQL)CREATE INDEX (Transact-SQL)

本主題適用於: 是SQL Server (從 2008 開始)是Azure SQL Database是Azure SQL 資料倉儲 是平行處理資料倉儲 THIS TOPIC APPLIES TO: yesSQL Server (starting with 2008)yesAzure SQL DatabaseyesAzure SQL Data Warehouse yesParallel Data Warehouse

在資料表或檢視表上建立關聯式索引。Creates a relational index on a table or view. 因為它是其中一個非叢集或非叢集 btree 索引時,也稱為資料列存放區索引。Also called a rowstore index because it is either a clustered or nonclustered btree index. 資料表中有資料之前,您可以建立資料列存放區索引。You can create a rowstore index before there is data in the table. 若要改善查詢效能,特別是在查詢從特定資料行中選取,或需要特定的順序排序值時,才使用資料列存放區索引。Use a rowstore index to improve query performance, especially when the queries select from specific columns or require values to be sorted in a particular order.

注意

Azure SQL 資料倉儲和平行處理資料倉儲目前不支援 Unique 條件約束。Azure SQL Data Warehouse and Parallel Data Warehouse currently do not support Unique constraints. 參考唯一的條件約束的任何範例僅適用於 SQL Server 和 Azure SQL DatabaseAny examples referencing Unique Constraints are only applicable to SQL Server and Azure SQL Database

簡單的範例:Simple examples:

-- Create a nonclustered index on a table or view  
CREATE INDEX i1 ON t1 (col1);  
--Create a clustered index on a table and use a 3-part name for the table  
CREATE CLUSTERED INDEX i1 ON d1.s1.t1 (col1);  
-- Syntax for SQL Server and Azure SQL Database
-- Create a nonclustered index with a unique constraint 
-- on 3 columns and specify the sort order for each column  
CREATE UNIQUE INDEX i1 ON t1 (col1 DESC, col2 ASC, col3 DESC);  

重要的案例:Key scenarios:

語法Syntax

-- Syntax for SQL Server and Azure SQL Database

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name   
    ON <object> ( column [ ASC | DESC ] [ ,...n ] )   
    [ INCLUDE ( column_name [ ,...n ] ) ]  
    [ WHERE <filter_predicate> ]  
    [ WITH ( <relational_index_option> [ ,...n ] ) ]  
    [ ON { partition_scheme_name ( column_name )   
         | filegroup_name   
         | default   
         }  
    ]  
    [ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]  

[ ; ]  

<object> ::=  
{  
    [ database_name. [ schema_name ] . | schema_name. ]   
    table_or_view_name  
}  

<relational_index_option> ::=  
{  
    PAD_INDEX = { ON | OFF }  
  | FILLFACTOR = fillfactor  
  | SORT_IN_TEMPDB = { ON | OFF }  
  | IGNORE_DUP_KEY = { ON | OFF }  
  | STATISTICS_NORECOMPUTE = { ON | OFF }  
  | STATISTICS_INCREMENTAL = { ON | OFF }  
  | DROP_EXISTING = { ON | OFF }  
  | ONLINE = { ON | OFF }  
  | ALLOW_ROW_LOCKS = { ON | OFF }  
  | ALLOW_PAGE_LOCKS = { ON | OFF }  
  | MAXDOP = max_degree_of_parallelism  
  | DATA_COMPRESSION = { NONE | ROW | PAGE}   
     [ ON PARTITIONS ( { <partition_number_expression> | <range> }   
     [ , ...n ] ) ]  
}  

<filter_predicate> ::=   
    <conjunct> [ AND <conjunct> ]  

<conjunct> ::=  
    <disjunct> | <comparison>  

<disjunct> ::=  
        column_name IN (constant ,...n)  

<comparison> ::=  
        column_name <comparison_op> constant  

<comparison_op> ::=  
    { IS | IS NOT | = | <> | != | > | >= | !> | < | <= | !< }  

<range> ::=   
<partition_number_expression> TO <partition_number_expression>  

Backward Compatible Relational Index  
Important   The backward compatible relational index syntax structure 
will be removed in a future version of SQL Server. Avoid using this 
syntax structure in new development work, and plan to modify 
applications that currently use the feature. Use the syntax structure 
specified in <relational_index_option> instead.  

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name   
    ON <object> ( column_name [ ASC | DESC ] [ ,...n ] )   
    [ WITH <backward_compatible_index_option> [ ,...n ] ]  
    [ ON { filegroup_name | "default" } ]  

<object> ::=  
{  
    [ database_name. [ owner_name ] . | owner_name. ]   
    table_or_view_name  
}  

<backward_compatible_index_option> ::=  
{   
    PAD_INDEX  
  | FILLFACTOR = fillfactor  
  | SORT_IN_TEMPDB  
  | IGNORE_DUP_KEY  
  | STATISTICS_NORECOMPUTE   
  | DROP_EXISTING   
}  
-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse  

CREATE [ CLUSTERED | NONCLUSTERED ] INDEX index_name   
    ON [ database_name . [ schema ] . | schema . ] table_name   
        ( { column [ ASC | DESC ] } [ ,...n ] )  
    WITH ( DROP_EXISTING = { ON | OFF } )  
[;]  

引數Arguments

UNIQUEUNIQUE
在資料表或檢視表上建立唯一索引。Creates a unique index on a table or view. 在唯一索引中,任兩個資料列都不能有相同的索引鍵值。A unique index is one in which no two rows are permitted to have the same index key value. 檢視表中的叢集索引必須是唯一的。A clustered index on a view must be unique.

不論 IGNORE_DUP_KEY 是否設為 ON, Database EngineDatabase Engine 都不允許在已包含重複值的資料行上建立唯一索引。The Database EngineDatabase Engine does not allow creating a unique index on columns that already include duplicate values, whether or not IGNORE_DUP_KEY is set to ON. 如果嘗試執行這項作業, Database EngineDatabase Engine 會顯示錯誤訊息。If this is tried, the Database EngineDatabase Engine displays an error message. 必須先移除重複值,才能在資料行上建立唯一索引。Duplicate values must be removed before a unique index can be created on the column or columns. 唯一索引中使用的資料行應設為 NOT NULL,因為當建立唯一索引時,多個 Null 值會被視為重複值。Columns that are used in a unique index should be set to NOT NULL, because multiple null values are considered duplicates when a unique index is created.

CLUSTEREDCLUSTERED
建立一個索引,在該索引中,索引鍵值的邏輯順序會決定資料表中對應資料列的實體順序。Creates an index in which the logical order of the key values determines the physical order of the corresponding rows in a table. 叢集索引的層級 (底部或分葉) 包含資料表的實際資料列。The bottom, or leaf, level of the clustered index contains the actual data rows of the table. 資料表或檢視表一次只允許一個叢集索引。A table or view is allowed one clustered index at a time.

含有唯一叢集索引的檢視表稱為索引檢視表。A view with a unique clustered index is called an indexed view. 在檢視表上建立唯一叢集索引,可將檢視表實際具體化。Creating a unique clustered index on a view physically materializes the view. 必須先在檢視表上建立唯一叢集索引,才能在相同檢視表上定義任何其他索引。A unique clustered index must be created on a view before any other indexes can be defined on the same view. 如需詳細資訊,請參閱 建立索引檢視表For more information, see Create Indexed Views.

先建立叢集索引,再建立任何非叢集索引。Create the clustered index before creating any nonclustered indexes. 當建立叢集索引時,會重建資料表上現有的非叢集索引。Existing nonclustered indexes on tables are rebuilt when a clustered index is created.

如果未指定 CLUSTERED,就會建立非叢集索引。If CLUSTERED is not specified, a nonclustered index is created.

注意

因為叢集的索引和資料頁的分葉層級是以相同方式定義,建立叢集的索引,並使用 ON partition_scheme_name或 ON filegroup_name子句有效從建立資料表的檔案群組的資料表移到新的分割區配置或檔案群組中。Because the leaf level of a clustered index and the data pages are the same by definition, creating a clustered index and using the ON partition_scheme_name or ON filegroup_name clause effectively moves a table from the filegroup on which the table was created to the new partition scheme or filegroup. 在特定檔案群組上建立資料表或索引之前,請先確認檔案群組是可用的,而且它們有足夠的空間可供索引使用。Before creating tables or indexes on specific filegroups, verify which filegroups are available and that they have enough empty space for the index.

在某些情況下,建立叢集索引可啟用先前停用的索引。In some cases creating a clustered index can enable previously disabled indexes. 如需詳細資訊,請參閱Enable Indexes and Constraints停用索引和條件約束For more information, see Enable Indexes and Constraints and Disable Indexes and Constraints.

非叢集NONCLUSTERED
建立索引來指定資料表的邏輯排序。Creates an index that specifies the logical ordering of a table. 如果是非叢集索引,資料列的實體順序和它們的索引順序無關。With a nonclustered index, the physical order of the data rows is independent of their indexed order.

不論索引的建立方式為何,每一份資料表最多只能有 999 個非叢集索引:以隱含的方式使用 PRIMARY KEY 和 UNIQUE 條件約束或以明確的方式使用 CREATE INDEX。Each table can have up to 999 nonclustered indexes, regardless of how the indexes are created: either implicitly with PRIMARY KEY and UNIQUE constraints, or explicitly with CREATE INDEX.

如果是索引檢視表,只能在已定義唯一叢集索引的檢視表上建立非叢集索引。For indexed views, nonclustered indexes can be created only on a view that has a unique clustered index already defined.

預設值是 NONCLUSTERED。The default is NONCLUSTERED.

index_nameindex_name
這是索引的名稱。Is the name of the index. 在資料表或檢視表內,索引名稱必須是唯一的,但在資料庫內就不一定要是唯一的。Index names must be unique within a table or view but do not have to be unique within a database. 索引名稱必須遵守的規則識別碼Index names must follow the rules of identifiers.

資料行column
這是做為索引根據的資料行。Is the column or columns on which the index is based. 您可以指定兩個或兩個以上的資料行名稱,在指定之資料行的合計值上建立複合索引。Specify two or more column names to create a composite index on the combined values in the specified columns. 列出要包含在複合的索引,排序優先權順序之後, 在括號內的資料行table_or_view_nameList the columns to be included in the composite index, in sort-priority order, inside the parentheses after table_or_view_name.

最多 32 個資料行可以結合成單一複合索引鍵。Up to 32 columns can be combined into a single composite index key. 複合索引鍵中的所有資料行都必須在相同的資料表或檢視表中。All the columns in a composite index key must be in the same table or view. 結合的索引值的允許大小上限是 900 個位元組的叢集索引或非叢集索引為 1,700。The maximum allowable size of the combined index values is 900 bytes for a clustered index, or 1,700 for a nonclustered index. 限制為 16 個資料行與之前的版本 900 個位元組 SQL DatabaseSQL DatabaseV12 和 SQL Server 2016SQL Server 2016The limits are 16 columns and 900 bytes for versions before SQL DatabaseSQL Database V12 and SQL Server 2016SQL Server 2016.

大型物件 (LOB) 資料類型的資料行ntext文字varchar (max)nvarchar (max)varbinary (max)xml,或映像不能指定為索引鍵資料行。Columns that are of the large object (LOB) data types ntext, text, varchar(max), nvarchar(max), varbinary(max), xml, or image cannot be specified as key columns for an index. 此外,不能包含檢視定義ntext文字,或映像資料行,即使它們不能以 CREATE INDEX 陳述式參考。Also, a view definition cannot include ntext, text, or image columns, even if they are not referenced in the CREATE INDEX statement.

如果 CLR 使用者定義型別支援二進位排序,您可以在該型別的資料行上建立索引。You can create indexes on CLR user-defined type columns if the type supports binary ordering. 只要方法標示為具決定性且不執行資料存取作業,您也可以在定義為使用者定義型別資料行方法引動過程的計算資料行上建立索引。You can also create indexes on computed columns that are defined as method invocations off a user-defined type column, as long as the methods are marked deterministic and do not perform data access operations. 如需有關 CLR 使用者定義型別資料行編製索引的詳細資訊,請參閱CLR 使用者定義型別For more information about indexing CLR user-defined type columns, see CLR User-defined Types.

[ ASC |DESC][ ASC | DESC ]
決定特定索引資料行的遞增或遞減排序方向。Determines the ascending or descending sort direction for the particular index column. 預設值是 ASC。The default is ASC.

包含(資料行[ ...n ] )INCLUDE (column [ ,... n ] )
指定要加入至非叢集索引分葉層級的非索引鍵資料行。Specifies the non-key columns to be added to the leaf level of the nonclustered index. 非叢集索引可以是唯一或非唯一的。The nonclustered index can be unique or non-unique.

資料行名稱在 INCLUDE 清單中不能重複,且不能同時做為索引鍵資料行和非索引鍵資料行。Column names cannot be repeated in the INCLUDE list and cannot be used simultaneously as both key and non-key columns. 如果資料表上有定義叢集索引,非叢集索引一定會包含叢集索引資料行。Nonclustered indexes always contain the clustered index columns if a clustered index is defined on the table. 如需詳細資訊,請參閱 建立內含資料行的索引For more information, see Create Indexes with Included Columns.

允許所有的資料類型,除了 textntextimage以外。All data types are allowed except text, ntext, and image. 必須建立或離線重建索引 (ONLINE = OFF) 所指定的非索引鍵資料任何的行一個是否varchar (max)nvarchar (max),或varbinary (max)資料型別。The index must be created or rebuilt offline (ONLINE = OFF) if any one of the specified non-key columns are varchar(max), nvarchar(max), or varbinary(max) data types.

具決定性之精確或非精確的計算資料行都可以當做內含資料行。Computed columns that are deterministic and either precise or imprecise can be included columns. 計算資料行,衍生自映像ntext文字varchar (max)nvarchar (max)varbinary (max),和xml資料類型可以包含非索引鍵資料行中,只要計算資料行資料類型時,才允許內含資料行。Computed columns derived from image, ntext, text, varchar(max), nvarchar(max), varbinary(max), and xml data types can be included in non-key columns as long as the computed column data types is allowable as an included column. 如需詳細資訊,請參閱 計算資料行的索引For more information, see Indexes on Computed Columns.

如需建立 XML 索引資訊,請參閱CREATE XML INDEX (TRANSACT-SQL ).For information on creating an XML index, see CREATE XML INDEX (Transact-SQL).

其中<filter_predicate > 藉由指定要在索引中包含的資料列建立篩選的索引。WHERE <filter_predicate> Creates a filtered index by specifying which rows to include in the index. 已篩選的索引必須是資料表上的非叢集索引。The filtered index must be a nonclustered index on a table. 針對已篩選之索引中的資料列建立已篩選的統計資料。Creates filtered statistics for the data rows in the filtered index.

篩選述詞會使用簡單比較邏輯,而且無法參考計算資料行、UDT 資料行、空間資料類型資料行或 hierarchyID 資料類型資料行。The filter predicate uses simple comparison logic and cannot reference a computed column, a UDT column, a spatial data type column, or a hierarchyID data type column. 比較運算子不允許使用 NULL 常值的比較。Comparisons using NULL literals are not allowed with the comparison operators. 請改用 IS NULL 和 IS NOT NULL 運算子。Use the IS NULL and IS NOT NULL operators instead.

下面是一些 Production.BillOfMaterials 資料表之篩選述詞的範例:Here are some examples of filter predicates for the Production.BillOfMaterials table:

  • WHERE StartDate > '20000101' AND EndDate <= '20000630'

  • WHERE ComponentID IN (533, 324, 753)

  • WHERE StartDate IN ('20000404', '20000905') AND EndDate IS NOT NULL

    已篩選的索引不適用於 XML 索引和全文檢索索引。Filtered indexes do not apply to XML indexes and full-text indexes. 如果是 UNIQUE 索引,只有選取的資料列必須有唯一的索引值。For UNIQUE indexes, only the selected rows must have unique index values. 已篩選的索引不允許 IGNORE_DUP_KEY 選項。Filtered indexes do not allow the IGNORE_DUP_KEY option.

    ON partition_scheme_name(column_name)ON partition_scheme_name(column_name)
    適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

    指定分割區配置來定義要做為分割區索引之分割區對應目標的檔案群組。Specifies the partition scheme that defines the filegroups onto which the partitions of a partitioned index will be mapped. 資料分割配置必須存在於資料庫中執行CREATE PARTITION SCHEMEALTER PARTITION SCHEMEThe partition scheme must exist within the database by executing either CREATE PARTITION SCHEME or ALTER PARTITION SCHEME. column_name指定資料分割的索引將會分割依據的資料行。column_name specifies the column against which a partitioned index will be partitioned. 此資料行必須符合資料類型、 長度和有效位數引數的資料分割函式, partition_scheme_name使用。This column must match the data type, length, and precision of the argument of the partition function that partition_scheme_name is using. column_name未限制為索引定義中的資料行。column_name is not restricted to the columns in the index definition. 基底資料表中的任何資料行都可以指定,但在分割唯一索引, column_name必須選擇從做的唯一索引鍵。Any column in the base table can be specified, except when partitioning a UNIQUE index, column_name must be chosen from among those used as the unique key. 這項限制可讓 Database EngineDatabase Engine 只在單一分割區內驗證索引鍵值的唯一性。This restriction allows the Database EngineDatabase Engine to verify uniqueness of key values within a single partition only.

注意

當您分割一個非唯一的叢集索引時,如果尚未指定分割區資料行,依預設, Database EngineDatabase Engine 會將它加入至叢集索引鍵清單。When you partition a non-unique, clustered index, the Database EngineDatabase Engine by default adds the partitioning column to the list of clustered index keys, if it is not already specified. 當您分割一個非唯一的非叢集索引時,如果尚未指定分割區資料行, Database EngineDatabase Engine 會將它新增為索引的非索引鍵 (內含) 資料行。When partitioning a non-unique, nonclustered index, the Database EngineDatabase Engine adds the partitioning column as a non-key (included) column of the index, if it is not already specified.

如果partition_scheme_name檔案群組未指定和資料表資料分割,此索引會放在相同的資料分割配置,使用相同的分割資料行,做為基礎的資料表。If partition_scheme_name or filegroup is not specified and the table is partitioned, the index is placed in the same partition scheme, using the same partitioning column, as the underlying table.

注意

您無法在 XML 索引上指定分割區配置。You cannot specify a partitioning scheme on an XML index. 如果基底資料表已分割,XML 索引會使用與資料表相同的分割區配置。If the base table is partitioned, the XML index uses the same partition scheme as the table.

如需有關資料分割索引, Partitioned Tables and IndexesFor more information about partitioning indexes, Partitioned Tables and Indexes.

ON filegroup_nameON filegroup_name
適用於SQL Server 2008SQL Server 2008SQL Server 2017SQL Server 2017Applies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017.

在指定的檔案群組上建立指定的索引。Creates the specified index on the specified filegroup. 如果未指定位置,且資料表或檢視表未分割,則索引會使用與基礎資料表或檢視表相同的檔案群組。If no location is specified and the table or view is not partitioned, the index uses the same filegroup as the underlying table or view. 此檔案群組必須已存在。The filegroup must already exist.

ON "預設"ON "default"
適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

在預設的檔案群組上建立指定的索引。Creates the specified index on the default filegroup.

在這個內容中,default 這個字不是關鍵字。The term default, in this context, is not a keyword. 它是預設檔案群組的識別碼,必須加以分隔,如 ON "預設"或 ON [預設]It is an identifier for the default filegroup and must be delimited, as in ON "default" or ON [default]. 如果指定了 "default",目前工作階段的 QUOTED_IDENTIFIER 選項就必須是 ON。If "default" is specified, the QUOTED_IDENTIFIER option must be ON for the current session. 這是預設值。This is the default setting. 如需詳細資訊,請參閱 SET QUOTED_IDENTIFIER (Transact-SQL)For more information, see SET QUOTED_IDENTIFIER (Transact-SQL).

[FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name |"NULL"}][ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
適用於SQL Server 2008SQL Server 2008SQL Server 2017SQL Server 2017Applies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017.

指定在建立叢集索引時,資料表之 FILESTREAM 資料的位置。Specifies the placement of FILESTREAM data for the table when a clustered index is created. FILESTREAM_ON 子句允許將 FILESTREAM 資料移到不同的 FILESTREAM 檔案群組或分割區配置。The FILESTREAM_ON clause allows FILESTREAM data to be moved to a different FILESTREAM filegroup or partition scheme.

filestream_filegroup_name是 FILESTREAM 檔案群組的名稱。filestream_filegroup_name is the name of a FILESTREAM filegroup. 此檔案群組必須有一個檔案群組使用檔案群組定義CREATE DATABASEALTER DATABASE陳述式; 否則就會引發錯誤。The filegroup must have one file defined for the filegroup by using a CREATE DATABASE or ALTER DATABASE statement; otherwise, an error is raised.

如果分割此資料表,則必須包含 FILESTREAM_ON 子句,而且必須指定 FILESTREAM 檔案群組的分割區配置,此配置會使用與資料表之分割區配置相同的分割區函數和分割區資料行。If the table is partitioned, the FILESTREAM_ON clause must be included and must specify a partition scheme of FILESTREAM filegroups that uses the same partition function and partition columns as the partition scheme for the table. 否則,就會引發錯誤。Otherwise, an error is raised.

如果此資料表未分割,FILESTREAM 資料行將無法分割。If the table is not partitioned, the FILESTREAM column cannot be partitioned. 此資料表的 FILESTREAM 資料必須儲存在 FILESTREAM_ON 子句中指定的單一檔案群組內。FILESTREAM data for the table must be stored in a single filegroup that is specified in the FILESTREAM_ON clause.

如果正在建立叢集索引,而且此資料表不包含 FILESTREAM 資料行,則可以在 CREATE INDEX 陳述式內指定 FILESTREAM_ON NULL。FILESTREAM_ON NULL can be specified in a CREATE INDEX statement if a clustered index is being created and the table does not contain a FILESTREAM column.

如需詳細資訊,請參閱 FILESTREAM (SQL Server)For more information, see FILESTREAM (SQL Server).

<物件 >:: =<object>::=

這是要建立索引的完整或非完整物件。Is the fully qualified or nonfully qualified object to be indexed.

database_namedatabase_name
這是資料庫的名稱。Is the name of the database.

schema_nameschema_name
這是資料表或檢視表所屬的結構描述名稱。Is the name of the schema to which the table or view belongs.

table_or_view_nametable_or_view_name
這是要建立索引之資料表或檢視表的名稱。Is the name of the table or view to be indexed.

必須利用 SCHEMABINDING 定義檢視表,才能在該檢視表上建立索引。The view must be defined with SCHEMABINDING to create an index on it. 必須先在檢視表上建立唯一叢集索引,才能建立任何非叢集索引。A unique clustered index must be created on a view before any nonclustered index is created. 如需有關索引檢視表的詳細資訊,請參閱「備註」一節。For more information about indexed views, see the Remarks section.

開頭為 SQL Server 2016SQL Server 2016,此物件可以儲存具有叢集資料行存放區索引的資料表。Beginning with SQL Server 2016SQL Server 2016, the object can be a table stored with a clustered columnstore index.

Azure SQL DatabaseAzure SQL Database支援三部分名稱格式database_name[schema_name]object_namedatabase_name是目前的資料庫或database_name是 tempdb 和object_name開頭為 #。 supports the three-part name format database_name.[schema_name].object_name when the database_name is the current database or the database_name is tempdb and the object_name starts with #.

<relational_index_option >:: =<relational_index_option>::=

指定當您建立索引時所需使用的選項。Specifies the options to use when you create the index.

PAD_INDEX = {ON |OFF }PAD_INDEX = { ON | OFF }
適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

指定索引填補。Specifies index padding. 預設值為 OFF。The default is OFF.

ONON
所指定的可用空間百分比填滿因數會套用到索引的中繼層級頁面。The percentage of free space that is specified by fillfactor is applied to the intermediate-level pages of the index.

關閉或填滿因數未指定OFF or fillfactor is not specified
中繼層級頁面會幾乎填滿整個容量,但會考量中繼頁面上的索引鍵集,而保留至少可供索引所能擁有之大小上限的一個資料列使用的足夠空間。The intermediate-level pages are filled to near capacity, leaving sufficient space for at least one row of the maximum size the index can have, considering the set of keys on the intermediate pages.

只有在指定 FILLFACTOR 時,才能使用 PAD_INDEX 選項,因為 PAD_INDEX 會使用 FILLFACTOR 所指定的百分比。The PAD_INDEX option is useful only when FILLFACTOR is specified, because PAD_INDEX uses the percentage specified by FILLFACTOR. 如果 FILLFACTOR 所指定的百分比不夠,無法允許一個資料列, Database EngineDatabase Engine 會在內部覆寫該百分比以允許最小值。If the percentage specified for FILLFACTOR is not large enough to allow for one row, the Database EngineDatabase Engine internally overrides the percentage to allow for the minimum. 中繼索引頁上的資料列數目絕不會是小於兩個,不論如何低的值為何填滿因數The number of rows on an intermediate index page is never less than two, regardless of how low the value of fillfactor.

在與舊版本相容的語法中,WITH PAD_INDEX 相當於 WITH PAD_INDEX = ON。In backward compatible syntax, WITH PAD_INDEX is equivalent to WITH PAD_INDEX = ON.

填滿因數 = 填滿因數FILLFACTOR =fillfactor
適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

指定用以指出建立或重建索引時, Database EngineDatabase Engine 填滿各索引頁面分葉層級之程度的百分比。Specifies a percentage that indicates how full the Database EngineDatabase Engine should make the leaf level of each index page during index creation or rebuild. 填滿因數必須是介於 1 到 100 之間的整數值。fillfactor must be an integer value from 1 to 100. 如果填滿因數是 100, Database EngineDatabase Engine會利用已填滿容量的分葉頁面建立索引。If fillfactor is 100, the Database EngineDatabase Engine creates indexes with leaf pages filled to capacity.

只有在建立或重建索引時才會套用 FILLFACTOR 設定。The FILLFACTOR setting applies only when the index is created or rebuilt. Database EngineDatabase Engine 不會動態保留頁面中空白空間的指定百分比。The Database EngineDatabase Engine does not dynamically keep the specified percentage of empty space in the pages. 若要檢視填滿因數設定,請使用sys.indexes目錄檢視。To view the fill factor setting, use the sys.indexes catalog view.

重要

利用小於 100 的 FILLFACTOR 來建立叢集索引,會影響資料所佔用的儲存空間數量,因為 Database EngineDatabase Engine 在建立叢集索引時會轉散發資料。Creating a clustered index with a FILLFACTOR less than 100 affects the amount of storage space the data occupies because the Database EngineDatabase Engine redistributes the data when it creates the clustered index.

如需詳細資訊,請參閱 指定索引的填滿因素For more information, see Specify Fill Factor for an Index.

SORT_IN_TEMPDB = {ON |OFF }SORT_IN_TEMPDB = { ON | OFF }
適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

指定是否要將暫時排序結果儲存在tempdbSpecifies whether to store temporary sort results in tempdb. 預設值為 OFF。The default is OFF.

ONON
用來建立索引的中繼排序結果會儲存在tempdbThe intermediate sort results that are used to build the index are stored in tempdb. 這可能會減少建立索引,如果所需的時間tempdb是一組不同的使用者資料庫以外的磁碟上。This may reduce the time required to create an index if tempdb is on a different set of disks than the user database. 不過,這會增加建立索引時所使用的磁碟空間量。However, this increases the amount of disk space that is used during the index build.

OFFOFF
中繼排序結果會儲存在與用來儲存索引相同的資料庫中。The intermediate sort results are stored in the same database as the index.

除了建立索引,請在使用者資料庫所需的空間tempdb還需要大約相同數量的額外空間來容納中繼排序結果。In addition to the space required in the user database to create the index, tempdb must have about the same amount of additional space to hold the intermediate sort results. 如需詳細資訊,請參閱索引的 SORT_IN_TEMPDB 選項For more information, see SORT_IN_TEMPDB Option For Indexes.

在與舊版本相容的語法中,WITH SORT_IN_TEMPDB 相當於 WITH SORT_IN_TEMPDB = ON。In backward compatible syntax, WITH SORT_IN_TEMPDB is equivalent to WITH SORT_IN_TEMPDB = ON.

IGNORE_DUP_KEY = {ON |OFF }IGNORE_DUP_KEY = { ON | OFF }
指定當插入作業嘗試將重複的索引鍵值插入唯一索引時所產生的錯誤回應。Specifies the error response when an insert operation attempts to insert duplicate key values into a unique index. IGNORE_DUP_KEY 選項只適用於在建立或重建索引之後所發生的插入作業。The IGNORE_DUP_KEY option applies only to insert operations after the index is created or rebuilt. 選項沒有任何作用,執行時CREATE INDEXALTER INDEX,或更新The option has no effect when executing CREATE INDEX, ALTER INDEX, or UPDATE. 預設值為 OFF。The default is OFF.

ONON
當重複的索引鍵值插入唯一索引時,就會出現警告訊息。A warning message will occur when duplicate key values are inserted into a unique index. 只有違反唯一性條件約束的資料列才會失敗。Only the rows violating the uniqueness constraint will fail.

OFFOFF
當重複的索引鍵值插入唯一索引時,就會出現錯誤訊息。An error message will occur when duplicate key values are inserted into a unique index. 整個 INSERT 作業將會回復。The entire INSERT operation will be rolled back.

若為針對檢視表所建立的索引、非唯一索引、XML 索引、空間索引和篩選索引,IGNORE_DUP_KEY 不得設為 ON。IGNORE_DUP_KEY cannot be set to ON for indexes created on a view, non-unique indexes, XML indexes, spatial indexes, and filtered indexes.

若要檢視 IGNORE_DUP_KEY,請使用sys.indexesTo view IGNORE_DUP_KEY, use sys.indexes.

在與舊版本相容的語法中,WITH IGNORE_DUP_KEY 相當於 WITH IGNORE_DUP_KEY = ON。In backward compatible syntax, WITH IGNORE_DUP_KEY is equivalent to WITH IGNORE_DUP_KEY = ON.

STATISTICS_NORECOMPUTE = {ON |OFF}STATISTICS_NORECOMPUTE = { ON | OFF}
指定是否要重新計算散發統計資料。Specifies whether distribution statistics are recomputed. 預設值為 OFF。The default is OFF.

ONON
不會自動重新計算過期的統計資料。Out-of-date statistics are not automatically recomputed.

OFFOFF
啟用自動統計資料更新。Automatic statistics updating are enabled.

若要還原自動統計資料更新,請將 STATISTICS_NORECOMPUTE 設為 OFF,或執行不含 NORECOMPUTE 子句的 UPDATE STATISTICS。To restore automatic statistics updating, set the STATISTICS_NORECOMPUTE to OFF, or execute UPDATE STATISTICS without the NORECOMPUTE clause.

重要

停用散發統計資料的自動重新計算,可防止查詢最佳化工具取得與資料表有關之查詢的最佳執行計畫。Disabling automatic recomputation of distribution statistics may prevent the query optimizer from picking optimal execution plans for queries involving the table.

在與舊版本相容的語法中,WITH STATISTICS_NORECOMPUTE 相當於 WITH STATISTICS_NORECOMPUTE = ON。In backward compatible syntax, WITH STATISTICS_NORECOMPUTE is equivalent to WITH STATISTICS_NORECOMPUTE = ON.

STATISTICS_INCREMENTAL = {ON |OFF }STATISTICS_INCREMENTAL = { ON | OFF }
ON,建立的統計資料是以每個分割區統計資料。When ON, the statistics created are per partition statistics. OFF,卸除統計資料樹狀結構和 SQL ServerSQL Server重新計算統計資料。When OFF, the statistics tree is dropped and SQL ServerSQL Server re-computes the statistics. 預設值是OFFThe default is OFF.

如果不支援每個分割區區的統計資料,則會忽略該選項,並產生警告。If per partition statistics are not supported the option is ignored and a warning is generated. 針對下列統計資料類型,不支援累加統計資料:Incremental stats are not supported for following statistics types:

  • 建立統計資料時,所使用的索引未與基底資料表進行分割區對齊。Statistics created with indexes that are not partition-aligned with the base table.

  • 在 AlwaysOn 可讀取次要資料庫上建立的統計資料。Statistics created on Always On readable secondary databases.

  • 在唯讀資料庫上建立的統計資料。Statistics created on read-only databases.

  • 在篩選的索引上建立的統計資料。Statistics created on filtered indexes.

  • 在檢視上建立的統計資料。Statistics created on views.

  • 在內部資料表上建立的統計資料。Statistics created on internal tables.

  • 使用空間索引或 XML 索引建立的統計資料。Statistics created with spatial indexes or XML indexes.

    DROP_EXISTING = {ON |OFF }DROP_EXISTING = { ON | OFF }
    是要卸除和重建現有的叢集或非叢集索引,以修改資料行規格,並保留相同名稱的索引選項。Is an option to drop and rebuild the existing clustered or nonclustered index with modified column specifications, and keep the same name for the index. 預設值為 OFF。The default is OFF.

    ONON
    若要卸除和重建現有索引中,必須具有相同的名稱做為參數指定index_nameSpecifies to drop and rebuild the existing index, which must have the same name as the parameter index_name.

    OFFOFF
    指定不卸除和重建現有的索引。Specifies not to drop and rebuild the existing index. 如果指定的索引名稱已經存在,SQL Server 就會顯示錯誤。SQL Server displays an error if the specified index name already exists.

    您可以利用 DROP_EXISTING,變更:With DROP_EXISTING, you can change:

  • 叢集資料列存放區索引的非叢集資料列存放區索引。A nonclustered rowstore index to a clustered rowstore index.

    With DROP_EXISTING,您無法變更:With DROP_EXISTING, you cannot change:

  • 非叢集資料列存放區索引做為叢集資料列存放區索引。A clustered rowstore index to a nonclustered rowstore index.

  • 任何類型的資料列存放區索引的叢集資料行存放區索引。A clustered columnstore index to any type of rowstore index.

    在與舊版本相容的語法中,WITH DROP_EXISTING 相當於 WITH DROP_EXISTING = ON。In backward compatible syntax, WITH DROP_EXISTING is equivalent to WITH DROP_EXISTING = ON.

    ONLINE = {ON |OFF }ONLINE = { ON | OFF }
    指定在索引作業期間,查詢和資料修改是否能夠使用基礎資料表和相關聯的索引。Specifies whether underlying tables and associated indexes are available for queries and data modification during the index operation. 預設值為 OFF。The default is OFF.

注意

MicrosoftMicrosoft SQL ServerSQL Server的所有版本都無法使用線上索引作業。Online index operations are not available in every edition of MicrosoftMicrosoft SQL ServerSQL Server. 如需 SQL ServerSQL Server 版本支援的功能清單,請參閱 SQL Server 2016 版本和支援的功能For a list of features that are supported by the editions of SQL ServerSQL Server, see Editions and Supported Features for SQL Server 2016.

ONON
索引作業持續期間不會保留長期資料表鎖定。Long-term table locks are not held for the duration of the index operation. 在索引作業的主要階段期間,來源資料表上只保留意圖共用 (IS) 鎖定。During the main phase of the index operation, only an Intent Share (IS) lock is held on the source table. 這可使基礎資料表和索引的查詢或更新能夠進行。This enables queries or updates to the underlying table and indexes to proceed. 在作業開始時,共用 (S) 鎖定會在來源物件上保留一段很短的時間。At the start of the operation, a Shared (S) lock is held on the source object for a very short period of time. 在作業結束時,如果正在建立非叢集索引,則有一段短時間會在來源上取得 S (共用) 鎖定;或者,當以線上方式建立或卸除叢集索引時,以及正在重建叢集索引或非叢集索引時,則會取得 SCH-M (結構描述修改) 鎖定。At the end of the operation, for a short period of time, an S (Shared) lock is acquired on the source if a nonclustered index is being created; or an SCH-M (Schema Modification) lock is acquired when a clustered index is created or dropped online and when a clustered or nonclustered index is being rebuilt. 建立本機暫存資料表的索引時,ONLINE 不可設為 ON。ONLINE cannot be set to ON when an index is being created on a local temporary table.

OFFOFF
在索引作業期間會套用資料表鎖定。Table locks are applied for the duration of the index operation. 建立、重建或卸除叢集索引的離線索引作業,或重建或卸除非叢集索引的離線索引作業,會取得資料表的結構描述修改 (Sch-M) 鎖定。An offline index operation that creates, rebuilds, or drops a clustered index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. 這可防止所有使用者在作業持續期間存取基礎資料表。This prevents all user access to the underlying table for the duration of the operation. 建立非叢集索引的離線索引作業會取得資料表的共用 (S) 鎖定。An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. 這可避免對基礎資料表進行更新,但仍可執行讀取作業,如 SELECT 陳述式。This prevents updates to the underlying table but allows read operations, such as SELECT statements.

如需詳細資訊,請參閱線上索引作業的運作方式For more information, see How Online Index Operations Work.

您可以採用線上方式建立索引,包括全域暫存資料表上的索引,但以下是例外狀況:Indexes, including indexes on global temp tables, can be created online with the following exceptions:

  • XML 索引XML index

  • 本機暫存資料表上的索引。Index on a local temp table.

  • 檢視表上的初始唯一叢集索引。Initial unique clustered index on a view.

  • 停用的叢集索引。Disabled clustered indexes.

  • 如果基礎資料表包含 LOB 資料類型的叢集的索引:映像ntext文字,以及空間類型。Clustered index if the underlying table contains LOB data types: image, ntext, text, and spatial types.

  • varchar (max)varbinary (max)資料行不能是索引的一部分。varchar(max) and varbinary(max) columns cannot be part of an index. SQL ServerSQL Server (開頭為 SQL Server 2012SQL Server 2012) 然後在 SQL DatabaseSQL Database,當資料表包含varchar (max)varbinary (max)可以有資料行,包含其他資料行的叢集索引建立或重新使用線上選項。In SQL ServerSQL Server (beginning with SQL Server 2012SQL Server 2012) and in SQL DatabaseSQL Database, when a table contains varchar(max) or varbinary(max) columns, a clustered index containing other columns, can be built or rebuilt using the ONLINE option. SQL DatabaseSQL Database不允許線上選項時,基底資料表包含varchar (max)varbinary (max)資料行。 does not permit the ONLINE option when the base table contains varchar(max) or varbinary(max) columns.

    如需詳細資訊,請參閱 Perform Index Operations OnlineFor more information, see Perform Index Operations Online.

    ALLOW_ROW_LOCKS = { ON |OFF}ALLOW_ROW_LOCKS = { ON | OFF }
    適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

    指定是否允許資料列鎖定。Specifies whether row locks are allowed. 預設值是 ON。The default is ON.

    ONON
    當存取索引時,允許資料列鎖定。Row locks are allowed when accessing the index. Database EngineDatabase Engine 會決定使用資料列鎖定的時機。The Database EngineDatabase Engine determines when row locks are used.

    OFFOFF
    不使用資料列鎖定。Row locks are not used.

    ALLOW_PAGE_LOCKS = { ON |OFF}ALLOW_PAGE_LOCKS = { ON | OFF }
    適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

    指定是否允許頁面鎖定。Specifies whether page locks are allowed. 預設值是 ON。The default is ON.

    ONON
    當存取索引時,允許頁面鎖定。Page locks are allowed when accessing the index. Database EngineDatabase Engine 會決定使用頁面鎖定的時機。The Database EngineDatabase Engine determines when page locks are used.

    OFFOFF
    不使用頁面鎖定。Page locks are not used.

    MAXDOP = max_degree_of_parallelismMAXDOP = max_degree_of_parallelism
    適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

    覆寫設定 max degree of parallelism 伺服器組態選項索引作業期間的組態選項。Overrides the Configure the max degree of parallelism Server Configuration Option configuration option for the duration of the index operation. 請利用 MAXDOP 來限制執行平行計畫所用的處理器數目。Use MAXDOP to limit the number of processors used in a parallel plan execution. 最大值是 64 個處理器。The maximum is 64 processors.

    max_degree_of_parallelism可以是:max_degree_of_parallelism can be:

    11
    隱藏平行計畫的產生。Suppresses parallel plan generation.

    >1>1
    根據目前的系統工作負載,將平行索引作業所使用的處理器數目上限,限制為所指定的數目或更少的數目。Restricts the maximum number of processors used in a parallel index operation to the specified number or fewer based on the current system workload.

    0 (預設值)0 (default)
    根據目前的系統工作負載,使用實際數目或比實際數目更少的處理器。Uses the actual number of processors or fewer based on the current system workload.

    如需詳細資訊,請參閱 設定平行索引作業For more information, see Configure Parallel Index Operations.

注意

並非每個版本都可使用平行索引作業 MicrosoftMicrosoft SQL ServerSQL ServerParallel index operations are not available in every edition of MicrosoftMicrosoft SQL ServerSQL Server. 如需 SQL ServerSQL Server 版本支援的功能清單,請參閱 SQL Server 2016 版本和支援的功能For a list of features that are supported by the editions of SQL ServerSQL Server, see Editions and Supported Features for SQL Server 2016.

DATA_COMPRESSIONDATA_COMPRESSION
針對指定的索引、分割區編號或分割區範圍指定資料壓縮選項。Specifies the data compression option for the specified index, partition number, or range of partitions. 選項如下:The options are as follows:

NONE
不壓縮索引或指定的分割區。Index or specified partitions are not compressed.

ROWROW
使用資料列壓縮來壓縮索引或指定的分割區。Index or specified partitions are compressed by using row compression.

PAGEPAGE
使用頁面壓縮來壓縮索引或指定的分割區。Index or specified partitions are compressed by using page compression.

如需有關壓縮的詳細資訊,請參閱資料壓縮For more information about compression, see Data Compression.

在資料分割上( {<編號運算式 > |<範圍 >}[ ,... n ] ) 適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseON PARTITIONS ( { <partition_number_expression> | <range> } [ ,...n ] ) Applies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

指定套用 DATA_COMPRESSION 設定的分割區。Specifies the partitions to which the DATA_COMPRESSION setting applies. 如果未分割此索引,ON PARTITIONS 引數將會產生錯誤。If the index is not partitioned, the ON PARTITIONS argument will generate an error. 如果未提供 ON PARTITIONS 子句,DATA_COMPRESSION 選項會套用到分割區索引的所有分割區。If the ON PARTITIONS clause is not provided, the DATA_COMPRESSION option applies to all partitions of a partitioned index.

<編號運算式 > 可以下列方式指定:<partition_number_expression> can be specified in the following ways:

  • 提供分割區的編號,例如:ON PARTITIONS (2)。Provide the number for a partition, for example: ON PARTITIONS (2).

  • 為數個個別分割區提供以逗號分隔的分割區編號,例如:ON PARTITIONS (1, 5)。Provide the partition numbers for several individual partitions separated by commas, for example: ON PARTITIONS (1, 5).

  • 同時提供範圍和個別分割區,例如:ON PARTITIONS (2, 4, 6 TO 8)。Provide both ranges and individual partitions, for example: ON PARTITIONS (2, 4, 6 TO 8).

    <範圍 > 可以指定為資料分割數分隔的例如: ON PARTITIONS (6 TO 8)。<range> can be specified as partition numbers separated by the word TO, for example: ON PARTITIONS (6 TO 8).

    若要為不同的分割區設定不同類型的資料壓縮,請指定 DATA_COMPRESSION 選項一次以上,例如:To set different types of data compression for different partitions, specify the DATA_COMPRESSION option more than once, for example:

REBUILD WITH   
(  
DATA_COMPRESSION = NONE ON PARTITIONS (1),   
DATA_COMPRESSION = ROW ON PARTITIONS (2, 4, 6 TO 8),   
DATA_COMPRESSION = PAGE ON PARTITIONS (3, 5)  
);  

備註Remarks

CREATE INDEX 陳述式的最佳化方式與其他任何查詢一樣。The CREATE INDEX statement is optimized like any other query. 若要儲存在 I/O 作業上,查詢處理器可以選擇掃描另一個索引,而不是執行資料表掃描。To save on I/O operations, the query processor may choose to scan another index instead of performing a table scan. 在某些情況下,排序作業可以省略。The sort operation may be eliminated in some situations. 在多處理器電腦上,CREATE INDEX 可以利用更多的處理器來執行與建立索引相關聯的掃描和排序作業,執行方式與其他查詢的執行方式相同。On multiprocessor computers CREATE INDEX can use more processors to perform the scan and sort operations associated with creating the index, in the same way as other queries do. 如需詳細資訊,請參閱 設定平行索引作業For more information, see Configure Parallel Index Operations.

如果資料庫復原模式設為大量記錄或簡單模式,建立索引作業就可以利用最低限度記錄。The create index operation can be minimally logged if the database recovery model is set to either bulk-logged or simple.

索引可以在暫存資料表上建立。Indexes can be created on a temporary table. 當資料表卸除或工作階段結束時,就會卸除索引。When the table is dropped or the session ends, the indexes are dropped.

索引支援擴充屬性。Indexes support extended properties.

叢集索引Clustered Indexes

若要在資料表 (堆積) 上建立叢集索引,或要卸除及重新建立現有的叢集索引,則資料庫中必須有可用的其他工作空間,才能容納資料排序和原始資料表或現有叢集索引資料的暫存複本。Creating a clustered index on a table (heap) or dropping and re-creating an existing clustered index requires additional workspace to be available in the database to accommodate data sorting and a temporary copy of the original table or existing clustered index data. 如需叢集索引的詳細資訊,請參閱建立叢集索引For more information about clustered indexes, see Create Clustered Indexes.

非叢集索引Nonclustered Indexes

開頭為 SQL Server 2016SQL Server 2016Azure SQL DatabaseAzure SQL Database,您可以儲存成叢集資料行存放區索引的資料表上建立非叢集索引。Beginning with SQL Server 2016SQL Server 2016 and in Azure SQL DatabaseAzure SQL Database, you can create a nonclustered index on a table stored as a clustered columnstore index. 如果您第一次建立非叢集索引儲存的資料表為堆積或叢集的索引,索引會持續保留,如果您稍後將資料表轉換成叢集資料行存放區索引。If you first create a nonclustered index on a table stored as a heap or clustered index, the index will persist if you later convert the table to a clustered columnstore index. 它也是不必要卸除叢集索引時重建叢集資料行存放區索引。It is also not necessary to drop the nonclustered index when you rebuild the clustered columnstore index.

限制事項:Limitations and Restrictions:

  • FILESTREAM_ON 選項無效,當您儲存成叢集資料行存放區索引的資料表上建立非叢集索引。The FILESTREAM_ON option is not valid when you create a nonclustered index on a table stored as a clustered columnstore index.

唯一索引Unique Indexes

如果唯一索引存在,每當插入作業新增資料時, Database EngineDatabase Engine 都會確認是否有重複的值。When a unique index exists, the Database EngineDatabase Engine checks for duplicate values each time data is added by a insert operations. 可能產生重複索引鍵值的插入作業會回復,且 Database EngineDatabase Engine 會顯示錯誤訊息。Insert operations that would generate duplicate key values are rolled back, and the Database EngineDatabase Engine displays an error message. 即使插入作業變更多個資料列但只造成一個重複的值,一樣會發生這種情況。This is true even if the insert operation changes many rows but causes only one duplicate. 如果嘗試輸入資料,而該資料有唯一索引,且該資料的 IGNORE_DUP_KEY 子句設為 ON,則只有違反 UNIQUE 索引規則的資料列會失敗。If an attempt is made to enter data for which there is a unique index and the IGNORE_DUP_KEY clause is set to ON, only the rows violating the UNIQUE index fail.

分割區索引Partitioned Indexes

分割區索引與分割區資料表的建立和維護方式類似,不過,跟一般索引一樣,分割區索引會當做個別資料庫物件來處理。Partitioned indexes are created and maintained in a similar manner to partitioned tables, but like ordinary indexes, they are handled as separate database objects. 未進行分割的資料表上可以有分割區索引;已進行分割的資料表上也可以有非分割區索引。You can have a partitioned index on a table that is not partitioned, and you can have a nonpartitioned index on a table that is partitioned.

如果您要在分割區資料表上建立索引,且不指定要從中放置索引的檔案群組,則索引的分割區方式與基礎資料表相同。If you are creating an index on a partitioned table, and do not specify a filegroup on which to place the index, the index is partitioned in the same manner as the underlying table. 這是因為索引及其基礎資料表預設會置於同一個檔案群組內,且索引會供相同分割區配置中,使用相同分割區資料行的分割區資料表使用。This is because indexes, by default, are placed on the same filegroups as their underlying tables, and for a partitioned table in the same partition scheme that uses the same partitioning columns. 當索引使用相同分割區配置及分割資料行的資料表時,則索引是對齊與資料表。When the index uses the same partition scheme and partitioning column as the table, the index is aligned with the table.

警告

您可以對包含超過 1,000 個分割區的資料表,建立及重建不以資料表為準的索引,但不予支援。Creating and rebuilding nonaligned indexes on a table with more than 1,000 partitions is possible, but is not supported. 此做法可能會導致在作業期間效能降低或耗用過多記憶體。Doing so may cause degraded performance or excessive memory consumption during these operations. 建議當分割區數超過 1,000 時,一律使用以資料表為準的索引。We recommend using only aligned indexes when the number of partitions exceed 1,000.

分割區不是唯一的叢集索引時若未指定分割區資料行, Database EngineDatabase Engine 預設會將其加入叢集索引鍵清單。When partitioning a non-unique, clustered index, the Database EngineDatabase Engine by default adds any partitioning columns to the list of clustered index keys, if not already specified.

您可以對分割區資料表建立索引檢視表,其方法與建立資料表索引相同。Indexed views can be created on partitioned tables in the same manner as indexes on tables. 如需有關分割區索引的詳細資訊,請參閱< Partitioned Tables and Indexes>。For more information about partitioned indexes, see Partitioned Tables and Indexes.

SQL Server 2017SQL Server 2017 並不會在建立或重建分割區索引之後掃描資料表中所有的資料列建立統計資料。In SQL Server 2017SQL Server 2017, statistics are not created by scanning all the rows in the table when a partitioned index is created or rebuilt. 反之,查詢最佳化工具會使用預設的採樣演算法來產生統計資料。Instead, the query optimizer uses the default sampling algorithm to generate statistics. 如果要在掃描資料表中所有資料列時取得分割區索引的統計資料,請使用 CREATE STATISTICS 或 UPDATE STATISTICS 搭配 FULLSCAN 子句。To obtain statistics on partitioned indexes by scanning all the rows in the table, use CREATE STATISTICS or UPDATE STATISTICS with the FULLSCAN clause.

篩選的索引Filtered Indexes

已篩選的索引是最佳化的非叢集索引,適用於從資料表選取小型資料列百分比的查詢使用。A filtered index is an optimized nonclustered index, suited for queries that select a small percentage of rows from a table. 它會使用篩選述詞,針對資料表中的部分資料建立索引。It uses a filter predicate to index a portion of the data in the table. 設計良好的已篩選索引可以提升查詢效能、降低儲存成本,並減少維護成本。A well-designed filtered index can improve query performance, reduce storage costs, and reduce maintenance costs.

需要已篩選之索引的 SET 選項Required SET Options for Filtered Indexes

每當發生下列任何一個狀況時,都需要必要值資料行中的 SET 選項:The SET options in the Required Value column are required whenever any of the following conditions occur:

  • 建立已篩選的索引。Create a filtered index.

  • INSERT、UPDATE、DELETE 或 MERGE 作業修改已篩選之索引中的資料。INSERT, UPDATE, DELETE, or MERGE operation modifies the data in a filtered index.

  • 篩選的索引用於查詢最佳化工具產生查詢計劃。The filtered index is used by the query optimizer to produce the query plan.

    Set 選項SET options 必要值Required value 預設伺服器值Default server value 預設值Default

    OLE DB 與 ODBC 值OLE DB and ODBC value
    預設值Default

    DB-Library 值DB-Library value
    ANSI_NULLSANSI_NULLS ONON ONON ONON OFFOFF
    ANSI_PADDINGANSI_PADDING ONON ONON ONON OFFOFF
    ANSI_WARNINGSANSI_WARNINGS ONON ONON ONON OFFOFF
    ARITHABORTARITHABORT ONON ONON OFFOFF OFFOFF
    CONCAT_NULL_YIELDS_NULLCONCAT_NULL_YIELDS_NULL ONON ONON ONON OFFOFF
    NUMERIC_ROUNDABORTNUMERIC_ROUNDABORT OFFOFF OFFOFF OFFOFF OFFOFF
    QUOTED_IDENTIFIERQUOTED_IDENTIFIER ONON ONON ONON OFFOFF

    當資料庫的相容性層級設定為 90 或更高層級時,將 ANSI_WARNINGS 設定為 ON 也會將 ARITHABORT 隱含設定為 ON。Setting ANSI_WARNINGS to ON implicitly sets ARITHABORT to ON when the database compatibility level is set to 90 or higher. 如果資料庫的相容性層級設定為 80 或更低,ARITHABORT 選項就必須明確地設定為 ON。If the database compatibility level is set to 80 or earlier, the ARITHABORT option must explicitly be set to ON.

    當 SET 選項不正確時,可能會發生下列狀況:If the SET options are incorrect, the following conditions can occur:

  • 不會建立已篩選的索引。The filtered index is not created.

  • Database EngineDatabase Engine 會產生錯誤,並回復可變更索引中資料的 INSERT、UPDATE、DELETE 或 MERGE 陳述式。The Database EngineDatabase Engine generates an error and rolls back INSERT, UPDATE, DELETE, or MERGE statements that change data in the index.

  • 查詢最佳化工具不會針對任何 Transact-SQL 陳述式考量執行計畫中的索引。Query optimizer does not consider the index in the execution plan for any Transact-SQL statements.

    如需篩選索引的詳細資訊,請參閱Create Filtered IndexesFor more information about Filtered Indexes, see Create Filtered Indexes.

空間索引Spatial Indexes

空間索引的相關資訊,請參閱CREATE SPATIAL INDEX (TRANSACT-SQL )空間索引概觀For information about spatial indexes, see CREATE SPATIAL INDEX (Transact-SQL) and Spatial Indexes Overview.

XML 索引XML Indexes

如需有關 XML 索引,請參閱CREATE XML INDEX (TRANSACT-SQL )XML 索引 (SQL Server ).For information about XML indexes see, CREATE XML INDEX (Transact-SQL) and XML Indexes (SQL Server).

索引鍵大小Index Key Size

叢集索引為 900 個位元組,而非叢集索引為 1,700 個位元組的索引鍵的大小上限。The maximum size for an index key is 900 bytes for a clustered index and 1,700 bytes for a nonclustered index. (之前 SQL DatabaseSQL DatabaseV12 和 SQL Server 2016SQL Server 2016限制永遠都是 900 個位元組。)上的索引varchar可以建立超過位元組限制的資料行,如果資料行中的現有資料不能超過限制時,索引會建立; 不過,後續的插入或更新動作所造成的資料行總計大小大於此限制將會失敗。(Before SQL DatabaseSQL Database V12 and SQL Server 2016SQL Server 2016 the limit was always 900 bytes.) Indexes on varchar columns that exceed the byte limit can be created if the existing data in the columns do not exceed the limit at the time the index is created; however, subsequent insert or update actions on the columns that cause the total size to be greater than the limit will fail. 叢集索引的索引鍵所包含的 varchar 資料行不能在 ROW_OVERFLOW_DATA 配置單位中有現有的資料。The index key of a clustered index cannot contain varchar columns that have existing data in the ROW_OVERFLOW_DATA allocation unit. 如果在 varchar 資料行上建立叢集索引,且現有的資料在 IN_ROW_DATA 配置單位中,則後續在可能發送資料非資料列的資料行上進行的插入或更新動作會失敗。If a clustered index is created on a varchar column and the existing data is in the IN_ROW_DATA allocation unit, subsequent insert or update actions on the column that would push the data off-row will fail.

非叢集索引可將非索引鍵資料行併入索引的分葉層級中。Nonclustered indexes can include non-key columns in the leaf level of the index. 這些資料行不會考慮 Database EngineDatabase Engine時計算索引鍵大小。These columns are not considered by the Database EngineDatabase Engine when calculating the index key size . 如需詳細資訊,請參閱 建立內含資料行的索引For more information, see Create Indexes with Included Columns.

注意

分割資料表時,如果分割區索引鍵資料行原本不存在非唯一的叢集索引中, Database EngineDatabase Engine 就會將它們加入至索引。When tables are partitioned, if the partitioning key columns are not already present in a non-unique clustered index, they are added to the index by the Database EngineDatabase Engine. 在非唯一的叢集索引中,索引資料行 (不計算包含的資料行) 再加上任何加入之分割區資料行的組合大小不得超過 1800 個位元組。The combined size of the indexed columns (not counting included columns), plus any added partitioning columns cannot exceed 1800 bytes in a non-unique clustered index.

計算資料行Computed Columns

索引可以在計算資料行上建立。Indexes can be created on computed columns. 此外,計算資料行可以有 PERSISTED 屬性。In addition, computed columns can have the property PERSISTED. 這表示 Database EngineDatabase Engine 會將計算值儲存在資料表中,並在更新計算資料行所根據的任何其他資料行時更新這些計算值。This means that the Database EngineDatabase Engine stores the computed values in the table, and updates them when any other columns on which the computed column depends are updated. Database EngineDatabase Engine 在資料行上建立某索引,且查詢中參考該索引時,它會使用這些保存值。The Database EngineDatabase Engine uses these persisted values when it creates an index on the column, and when the index is referenced in a query.

若要為計算資料行建立索引,則計算資料行必須具決定性且精確。To index a computed column, the computed column must deterministic and precise. 不過,您可以利用 PERSISTED 屬性,擴充可建立索引的計算資料行類型,使其包括:However, using the PERSISTED property expands the type of indexable computed columns to include:

  • 根據 Transact-SQLTransact-SQL 和 CLR 函數及使用者標示為具決定性的 CLR 使用者定義型別方法所產生的計算資料行。Computed columns based on Transact-SQLTransact-SQL and CLR functions and CLR user-defined type methods that are marked deterministic by the user.

  • 根據具決定性 (如 Database EngineDatabase Engine 所定義) 但不精確的運算式所產生的計算資料行。Computed columns based on expressions that are deterministic as defined by the Database EngineDatabase Engine but imprecise.

    保存的計算資料行需要設定前一節<需要索引檢視表的 SET 選項>中所示的下列 SET 選項。Persisted computed columns require the following SET options to be set as shown in the previous section "Required SET Options for Indexed Views".

    UNIQUE 或 PRIMARY KEY 條件約束只要符合索引作業的所有條件就可以包含計算資料行。The UNIQUE or PRIMARY KEY constraint can contain a computed column as long as it satisfies all conditions for indexing. 更具體的說法是,計算資料行必須具決定性且精確,或是具決定性且一直保存。Specifically, the computed column must be deterministic and precise or deterministic and persisted. 如需決定性的詳細資訊,請參閱決定性與非決定性函數For more information about determinism, see Deterministic and Nondeterministic Functions.

    計算資料行,衍生自映像ntext文字varchar (max)nvarchar (max)varbinary (max),和xml資料類型可以建立索引做為索引鍵或內含非索引鍵資料行,只要計算資料行資料類型時,才允許做為索引鍵資料行或非索引鍵資料行。Computed columns derived from image, ntext, text, varchar(max), nvarchar(max), varbinary(max), and xml data types can be indexed either as a key or included non-key column as long as the computed column data type is allowable as an index key column or non-key column. 例如,您無法建立主要 XML 索引上計算xml資料行。For example, you cannot create a primary XML index on a computed xml column. 如果索引鍵大小超過 900 個位元組,畫面上會顯示警告訊息。If the index key size exceeds 900 bytes, a warning message is displayed.

    在計算資料行上建立索引,可能會使先前有效的插入或更新作業失敗。Creating an index on a computed column may cause the failure of an insert or update operation that previously worked. 當計算資料行導致算術錯誤時,就可能發生這類失敗。Such a failure may take place when the computed column results in arithmetic error. 例如在下表中,雖然計算資料行 c 導致算術錯誤,但 INSERT 陳述式仍可運作。For example, in the following table, although computed column c results in an arithmetic error, the INSERT statement works.

CREATE TABLE t1 (a int, b int, c AS a/b);  
INSERT INTO t1 VALUES (1, 0);  

但是,如果在建立資料表之後,您在計算資料行 c 上建立索引,相同的 INSERT 陳述式在這種情況下則會失敗。If, instead, after creating the table, you create an index on computed column c, the same INSERT statement will now fail.

CREATE TABLE t1 (a int, b int, c AS a/b);  
CREATE UNIQUE CLUSTERED INDEX Idx1 ON t1(c);  
INSERT INTO t1 VALUES (1, 0);  

如需詳細資訊,請參閱 計算資料行的索引For more information, see Indexes on Computed Columns.

將資料行併入索引中Included Columns in Indexes

您可以將非索引鍵資料行 (稱為內含資料行) 加入至非叢集索引的分葉層級,以處理查詢來提升查詢效能。Non-key columns, called included columns, can be added to the leaf level of a nonclustered index to improve query performance by covering the query. 換句話說,查詢中參考的所有資料行都會併入索引中當做索引鍵資料行或非索引鍵資料行。That is, all columns referenced in the query are included in the index as either key or non-key columns. 這可讓查詢最佳化工具從索引掃描中尋找所有的必要資訊;但不存取資料表或叢集索引。This allows the query optimizer to locate all the required information from an index scan; the table or clustered index data is not accessed. 如需詳細資訊,請參閱 建立內含資料行的索引For more information, see Create Indexes with Included Columns.

指定索引選項Specifying Index Options

SQL Server 2005SQL Server 2005 導入新的索引選項,並修改選項的指定方式。 introduced new index options and also modifies the way in which options are specified. 在回溯相容語法中,WITH option_name相當於 WITH ( <option_name > = ON ).In backward compatible syntax, WITH option_name is equivalent to WITH ( <option_name> = ON ). 當您設定索引選項時,適用下列規則:When you set index options, the following rules apply:

  • 新的索引選項只能指定使用 WITH (option_name = ON |關閉)New index options can only be specified by using WITH (option_name= ON | OFF).

  • 不能在相同的陳述式中同時利用與舊版本相容的語法和新語法來指定選項。Options cannot be specified by using both the backward compatible and new syntax in the same statement. 例如,指定 WITH (DROP_EXISTING線上 = ON)會導致陳述式失敗。For example, specifying WITH (DROP_EXISTING, ONLINE = ON) causes the statement to fail.

  • 當您建立 XML 索引時,必須使用與指定的選項(option_name = ON |關閉)When you create an XML index, the options must be specified by using WITH (option_name= ON | OFF).

DROP_EXISTING 子句DROP_EXISTING Clause

您可以利用 DROP_EXISTING 子句來重建索引、加入或卸除資料行、修改選項、修改資料行排序次序,或變更分割區配置或檔案群組。You can use the DROP_EXISTING clause to rebuild the index, add or drop columns, modify options, modify column sort order, or change the partition scheme or filegroup.

如果索引強制執行 PRIMARY KEY 或 UNIQUE 條件約束,且索引定義完全沒有變更,則會卸除索引並重新建立索引以保留現有的條件約束。If the index enforces a PRIMARY KEY or UNIQUE constraint and the index definition is not altered in any way, the index is dropped and re-created preserving the existing constraint. 不過,如果索引定義變更了,陳述式就會失敗。However, if the index definition is altered the statement fails. 若要變更 PRIMARY KEY 或 UNIQUE 條件約束的定義,請卸除該條件約束,然後利用新的定義來新增條件約束。To change the definition of a PRIMARY KEY or UNIQUE constraint, drop the constraint and add a constraint with the new definition.

當您在一份也有非叢集索引的資料表上利用一組相同或不同的索引鍵來重新建立叢集索引時,DROP_EXISTING 可以增強效能。DROP_EXISTING enhances performance when you re-create a clustered index, with either the same or different set of keys, on a table that also has nonclustered indexes. DROP_EXISTING 會取代舊叢集索引上之 DROP INDEX 陳述式的執行,然後再針對新叢集索引執行 CREATE INDEX 陳述式。DROP_EXISTING replaces the execution of a DROP INDEX statement on the old clustered index followed by the execution of a CREATE INDEX statement for the new clustered index. 非叢集索引只重建一次,之後,只有在索引定義變更時才會再重建。The nonclustered indexes are rebuilt once, and then only if the index definition has changed. 當索引定義的索引名稱、索引鍵資料行和分割區資料行、唯一性屬性及排序次序與原始索引相同時,DROP_EXISTING 子句不會重建非叢集索引。The DROP_EXISTING clause does not rebuild the nonclustered indexes when the index definition has the same index name, key and partition columns, uniqueness attribute, and sort order as the original index.

不論非叢集索引是否重建,它們一律會保留在它們的原始檔案群組或分割區配置中,且會使用原始的分割區函數。Whether the nonclustered indexes are rebuilt or not, they always remain in their original filegroups or partition schemes and use the original partition functions. 如果將叢集索引重建至不同的檔案群組或分割區配置中,則不會移動非叢集索引來符合叢集索引的新位置。If a clustered index is rebuilt to a different filegroup or partition scheme, the nonclustered indexes are not moved to coincide with the new location of the clustered index. 因此,即使非叢集索引先前與叢集索引對齊,它們也可能不再與叢集索引對齊。Therefore, even the nonclustered indexes previously aligned with the clustered index, they may no longer be aligned with it. 如需有關分割區索引對齊的詳細資訊,請參閱。For more information about partitioned index alignment, see.

除非索引陳述式指定非叢集索引且 ONLINE 選項設為 OFF,否則,如果您以相同的順序使用相同的索引鍵資料行,且相同的索引鍵資料行含有相同的遞增或遞減順序,則 DROP_EXISTING 子句不會再次排序資料。The DROP_EXISTING clause will not sort the data again if the same index key columns are used in the same order and with the same ascending or descending order, unless the index statement specifies a nonclustered index and the ONLINE option is set to OFF. 如果叢集索引已停用,則執行 CREATE INDEX WITH DROP_EXISTING 作業時必須將 ONLINE 設為 OFF。If the clustered index is disabled, the CREATE INDEX WITH DROP_EXISTING operation must be performed with ONLINE set to OFF. 如果非叢集索引已停用,且與停用的叢集索引無關,則執行 CREATE INDEX WITH DROP_EXISTING 作業時可以將 ONLINE 設為 OFF,也可以將它設為 ON。If a nonclustered index is disabled and is not associated with a disabled clustered index, the CREATE INDEX WITH DROP_EXISTING operation can be performed with ONLINE set to OFF or ON.

當卸除或重新建立含有 128 個 (含) 以上之範圍的索引時, Database EngineDatabase Engine 會延遲實際的頁面取消配置及其相關聯的鎖定,直到認可交易之後。When indexes with 128 extents or more are dropped or rebuilt, the Database EngineDatabase Engine defers the actual page deallocations, and their associated locks, until after the transaction commits.

ONLINE 選項ONLINE Option

以線上方式執行索引作業時,適用下列方針:The following guidelines apply for performing index operations online:

  • 當線上索引作業進行中時,不能變更、截斷或卸除基礎資料表。The underlying table cannot be altered, truncated, or dropped while an online index operation is in process.

  • 在索引作業進行期間,需要其他暫存磁碟空間。Additional temporary disk space is required during the index operation.

  • 線上作業可在下列索引上執行:分割區索引,以及包含保存的計算資料行或內含資料行的索引。Online operations can be performed on partitioned indexes and indexes that contain persisted computed columns, or included columns.

    如需詳細資訊,請參閱 Perform Index Operations OnlineFor more information, see Perform Index Operations Online.

資料列和頁面鎖定選項Row and Page Locks Options

如果 ALLOW_ROW_LOCKS = ON 且 ALLOW_PAGE_LOCK = ON,當您在存取索引時,允許使用資料列、頁面和資料表層級的鎖定。When ALLOW_ROW_LOCKS = ON and ALLOW_PAGE_LOCK = ON, row-, page-, and table-level locks are allowed when accessing the index. Database EngineDatabase Engine 會選擇適當的鎖定,且可以將鎖定從資料列或頁面鎖定擴大到資料表鎖定。The Database EngineDatabase Engine chooses the appropriate lock and can escalate the lock from a row or page lock to a table lock.

如果 ALLOW_ROW_LOCKS = OFF 且 ALLOW_PAGE_LOCK = OFF,當您存取索引時,只允許使用資料表層級的鎖定。When ALLOW_ROW_LOCKS = OFF and ALLOW_PAGE_LOCK = OFF, only a table-level lock is allowed when accessing the index.

檢視索引資訊Viewing Index Information

若要傳回有關索引的資訊,您可以使用目錄檢視、系統函數和系統預存程序。To return information about indexes, you can use catalog views, system functions, and system stored procedures.

資料壓縮Data Compression

主題會說明資料壓縮資料壓縮Data compression is described in the topic Data Compression. 以下是考量的幾個要點:The following are key points to consider:

  • 壓縮可讓更多的資料列儲存在頁面上,但是不會變更最大資料列大小。Compression can allow more rows to be stored on a page, but does not change the maximum row size.

  • 索引的非分葉頁面不會進行頁面壓縮,但是可以進行資料列壓縮。Non-leaf pages of an index are not page compressed but can be row compressed.

  • 每一個非叢集索引都有個別的壓縮設定,而且不會繼承基礎資料表的壓縮設定。Each nonclustered index has an individual compression setting, and does not inherit the compression setting of the underlying table.

  • 在堆積上建立叢集索引時,此叢集索引會繼承堆積的壓縮狀態,除非指定了替代的壓縮狀態。When a clustered index is created on a heap, the clustered index inherits the compression state of the heap unless an alternative compression state is specified.

    下列限制適用於分割區索引:The following restrictions apply to partitioned indexes:

  • 您無法在資料表具有非對齊索引時變更單一分割區的壓縮設定。You cannot change the compression setting of a single partition if the table has nonaligned indexes.

  • ALTER INDEX<索引 >...REBUILD PARTITION ... 語法會重建此索引的指定資料分割。The ALTER INDEX <index> ... REBUILD PARTITION ... syntax rebuilds the specified partition of the index.

  • ALTER INDEX<索引 >...REBUILD WITH ... 語法會重建此索引的所有資料分割。The ALTER INDEX <index> ... REBUILD WITH ... syntax rebuilds all partitions of the index.

    若要評估變更壓縮狀態如何影響資料表、索引或分割區,請使用 sp_estimate_data_compression_savings 預存程序。To evaluate how changing the compression state will affect a table, an index, or a partition, use the sp_estimate_data_compression_savings stored procedure.

PermissionsPermissions

需要資料表或檢視表的 ALTER 權限。Requires ALTER permission on the table or view. 使用者必須是 系統管理員 固定伺服器角色的成員,或是 db_ddladmindb_owner 固定資料庫角色的成員。User must be a member of the sysadmin fixed server role or the db_ddladmin and db_owner fixed database roles.

限制事項Limitations and Restrictions

SQL 資料倉儲SQL Data Warehouse平行處理資料倉儲Parallel Data Warehouse,您無法建立: and 平行處理資料倉儲Parallel Data Warehouse, you cannot create:

  • 資料倉儲資料表已存在的資料行存放區索引上的叢集或非叢集資料列存放區索引。A clustered or nonclustered rowstore index on a data warehouse table when a columnstore index already exists. 此行為是不同於 SMP SQL Server 可讓要共存於相同的資料表上的資料列存放區和資料行存放區索引。This behavior is different from SMP SQL Server which allows both rowstore and columnstore indexes to co-exist on the same table.

  • 您無法在檢視上建立索引。You cannot create an index on a view.

中繼資料Metadata

若要檢視現有索引上的資訊,您可以查詢sys.indexes (TRANSACT-SQL )目錄檢視。To view information on existing indexes, you can query the sys.indexes (Transact-SQL) catalog view.

版本資訊Version Notes

SQL Database 不支援的檔案群組和 filestream 選項。SQL Database does not support filegroup and filestream options.

範例: 所有版本。Examples: All versions. 使用的 AdventureWorks 資料庫。Uses the AdventureWorks database.

A.A. 建立簡單的非叢集資料列存放區索引Create a simple nonclustered rowstore index

下列範例會建立非叢集索引上VendorID資料行Purchasing.ProductVendor資料表。The following examples create a nonclustered index on the VendorID column of the Purchasing.ProductVendor table.

CREATE INDEX IX_VendorID ON ProductVendor (VendorID);  
CREATE INDEX IX_VendorID ON dbo.ProductVendor (VendorID DESC, Name ASC, Address DESC);  
CREATE INDEX IX_VendorID ON Purchasing..ProductVendor (VendorID);  

B.B. 建立簡單的非叢集資料列存放區的複合索引Create a simple nonclustered rowstore composite index

下列範例會建立非叢集複合索引上SalesQuotaSalesYTD的資料行Sales.SalesPerson資料表。The following example creates a nonclustered composite index on the SalesQuota and SalesYTD columns of the Sales.SalesPerson table.

CREATE NONCLUSTERED INDEX IX_SalesPerson_SalesQuota_SalesYTD ON Sales.SalesPerson (SalesQuota, SalesYTD);  

C.C. 另一個資料庫中的資料表上建立索引Create an index on a table in another database

下列範例會建立非叢集索引上VendorID資料行ProductVendor資料表中Purchasing資料庫。The following example creates a non-clustered index on the VendorID column of the ProductVendor table in the Purchasing database.

CREATE CLUSTERED INDEX IX_ProductVendor_VendorID ON Purchasing..ProductVendor (VendorID);   

D.D. 資料行加入索引Add a column to an index

下列範例會建立索引 IX_FF 含有 dbo 的兩個資料行。FactFinance 資料表。The following example creates index IX_FF with two columns from the dbo.FactFinance table. 下一個陳述式會重建多個資料行索引,並保留現有的名稱。The next statement rebuilds the index with one more column and keeps the existing name.

CREATE INDEX IX_FF ON dbo.FactFinance ( FinanceKey ASC, DateKey ASC );  

--Rebuild and add the OrganizationKey  
CREATE INDEX IX_FF ON dbo.FactFinance ( FinanceKey, DateKey, OrganizationKey DESC)  
WITH ( DROP_EXISTING = ON );  

範例: SQL Server 的 Azure SQL DatabaseExamples: SQL Server, Azure SQL Database

E.E. 建立唯一的非叢集索引Create a unique nonclustered index

下列範例會在 AdventureWorks2012AdventureWorks2012 資料庫中 Name 資料表的 Production.UnitMeasure 資料行上建立唯一非叢集索引。The following example creates a unique nonclustered index on the Name column of the Production.UnitMeasure table in the AdventureWorks2012AdventureWorks2012 database. 索引會強制將資料上的唯一性插入 Name 資料行中。The index will enforce uniqueness on the data inserted into the Name column.

CREATE UNIQUE INDEX AK_UnitMeasure_Name   
    ON Production.UnitMeasure(Name);  

下列查詢會藉由嘗試插入與現有資料列具有相同值的資料列,以測試條件約束的唯一性。The following query tests the uniqueness constraint by attempting to insert a row with the same value as that in an existing row.

--Verify the existing value.  
SELECT Name FROM Production.UnitMeasure WHERE Name = N'Ounces';  
GO  
INSERT INTO Production.UnitMeasure (UnitMeasureCode, Name, ModifiedDate)  
    VALUES ('OC', 'Ounces', GetDate());  

產生的錯誤訊息如下:The resulting error message is:

Server: Msg 2601, Level 14, State 1, Line 1  
Cannot insert duplicate key row in object 'UnitMeasure' with unique index 'AK_UnitMeasure_Name'. The statement has been terminated.  

F.F. 使用 IGNORE_DUP_KEY 選項Use the IGNORE_DUP_KEY option

下列範例分別利用兩種不同的選項設定 (先將選項設為 IGNORE_DUP_KEY,再將選項設為 ON) 將多個資料列插入暫存資料表中,示範 OFF 選項的效果。The following example demonstrates the effect of the IGNORE_DUP_KEY option by inserting multiple rows into a temporary table first with the option set to ON and again with the option set to OFF. 單一資料列會插入 #Test 資料表中,該資料表則會在第二個多重資料列 INSERT 陳述式執行時刻意造成重複的值。A single row is inserted into the #Test table that will intentionally cause a duplicate value when the second multiple-row INSERT statement is executed. 資料表中的資料列計數會傳回所插入的資料列數目。A count of rows in the table returns the number of rows inserted.

CREATE TABLE #Test (C1 nvarchar(10), C2 nvarchar(50), C3 datetime);  
GO  
CREATE UNIQUE INDEX AK_Index ON #Test (C2)  
    WITH (IGNORE_DUP_KEY = ON);  
GO  
INSERT INTO #Test VALUES (N'OC', N'Ounces', GETDATE());  
INSERT INTO #Test SELECT * FROM Production.UnitMeasure;  
GO  
SELECT COUNT(*)AS [Number of rows] FROM #Test;  
GO  
DROP TABLE #Test;  
GO  

以下是第二個 INSERT 陳述式的結果。Here are the results of the second INSERT statement.

Server: Msg 3604, Level 16, State 1, Line 5 Duplicate key was ignored.  

Number of rows   
--------------   
38  

請注意,從 Production.UnitMeasure 資料表插入之未違反唯一性條件約束的資料列已順利插入。Notice that the rows inserted from the Production.UnitMeasure table that did not violate the uniqueness constraint were successfully inserted. 發出警告且忽略重複的資料列,但不回復整個交易。A warning was issued and the duplicate row ignored, but the entire transaction was not rolled back.

重新執行相同的陳述式,但將 IGNORE_DUP_KEY 設為 OFFThe same statements are executed again, but with IGNORE_DUP_KEY set to OFF.

CREATE TABLE #Test (C1 nvarchar(10), C2 nvarchar(50), C3 datetime);  
GO  
CREATE UNIQUE INDEX AK_Index ON #Test (C2)  
    WITH (IGNORE_DUP_KEY = OFF);  
GO  
INSERT INTO #Test VALUES (N'OC', N'Ounces', GETDATE());  
INSERT INTO #Test SELECT * FROM Production.UnitMeasure;  
GO  
SELECT COUNT(*)AS [Number of rows] FROM #Test;  
GO  
DROP TABLE #Test;  
GO  

以下是第二個 INSERT 陳述式的結果。Here are the results of the second INSERT statement.

Server: Msg 2601, Level 14, State 1, Line 5  
Cannot insert duplicate key row in object '#Test' with unique index  
'AK_Index'. The statement has been terminated.  

Number of rows   
--------------   
1  

請注意,即便 Production.UnitMeasure 資料表只有一個資料列違反 UNIQUE 索引條件約束,皆會導致資料表中所有的資料列無法插入資料表。Notice that none of the rows from the Production.UnitMeasure table were inserted into the table even though only one row in the table violated the UNIQUE index constraint.

G.G. 使用 DROP_EXISTING 卸除及重新建立索引Using DROP_EXISTING to drop and re-create an index

下列範例會利用 ProductID 選項,在 AdventureWorks2012AdventureWorks2012 資料庫中 Production.WorkOrder 資料表的 DROP_EXISTING 資料行上卸除及重新建立現有的索引。The following example drops and re-creates an existing index on the ProductID column of the Production.WorkOrder table in the AdventureWorks2012AdventureWorks2012 database by using the DROP_EXISTING option. 也會設定 FILLFACTORPAD_INDEX 選項。The options FILLFACTOR and PAD_INDEX are also set.

CREATE NONCLUSTERED INDEX IX_WorkOrder_ProductID  
    ON Production.WorkOrder(ProductID)  
    WITH (FILLFACTOR = 80,  
        PAD_INDEX = ON,  
        DROP_EXISTING = ON);  
GO  

H.H. 在檢視上建立索引Create an index on a view

下列範例會在該檢視表上建立檢視表和索引。The following example creates a view and an index on that view. 內含使用索引檢視的兩項查詢。Two queries are included that use the indexed view.

--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  
--This query can use the indexed view even though the view is   
--not specified in the FROM clause.  
SELECT SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Rev,   
    OrderDate, ProductID  
FROM Sales.SalesOrderDetail AS od  
    JOIN Sales.SalesOrderHeader AS o ON od.SalesOrderID=o.SalesOrderID  
        AND ProductID BETWEEN 700 and 800  
        AND OrderDate >= CONVERT(datetime,'05/01/2002',101)  
GROUP BY OrderDate, ProductID  
ORDER BY Rev DESC;  
GO  
--This query can use the above indexed view.  
SELECT  OrderDate, SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Rev  
FROM Sales.SalesOrderDetail AS od  
    JOIN Sales.SalesOrderHeader AS o ON od.SalesOrderID=o.SalesOrderID  
        AND DATEPART(mm,OrderDate)= 3  
        AND DATEPART(yy,OrderDate) = 2002  
GROUP BY OrderDate  
ORDER BY OrderDate ASC;  
GO  

I.I. 建立內含 (非索引鍵) 資料行索引Create an index with included (non-key) columns

下列範例會利用一個索引鍵資料行 (PostalCode) 和四個非索引鍵資料行 (AddressLine1AddressLine2CityStateProvinceID) 來建立非叢集索引。The following example creates a nonclustered index with one key column (PostalCode) and four non-key columns (AddressLine1, AddressLine2, City, StateProvinceID). 其後有一個由索引處理的查詢。A query that is covered by the index follows. 若要顯示所選取的查詢最佳化工具在索引查詢功能表 Transact-SQLSQL Server Management Studio,選取顯示實際執行計畫之前執行查詢。To display the index that is selected by the query optimizer, on the Query menu in Transact-SQLSQL Server Management Studio, select Display Actual Execution Plan before executing the query.

CREATE NONCLUSTERED INDEX IX_Address_PostalCode  
    ON Person.Address (PostalCode)  
    INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID);  
GO  
SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCode  
FROM Person.Address  
WHERE PostalCode BETWEEN N'98000' and N'99999';  
GO  

J.J. 建立資料分割的索引Create a partitioned index

下列範例會在 AdventureWorks2012AdventureWorks2012 資料庫中現有的分割區配置 TransactionsPS1 上建立非叢集分割區索引。The following example creates a nonclustered partitioned index on TransactionsPS1, an existing partition scheme in the AdventureWorks2012AdventureWorks2012 database. 此範例假設您已安裝分割區索引範例。This example assumes the partitioned index sample has been installed.

適用於: SQL Server 2008SQL Server 2008透過 SQL Server 2017SQL Server 2017Azure SQL DatabaseAzure SQL DatabaseApplies to: SQL Server 2008SQL Server 2008 through SQL Server 2017SQL Server 2017 and Azure SQL DatabaseAzure SQL Database.

CREATE NONCLUSTERED INDEX IX_TransactionHistory_ReferenceOrderID  
    ON Production.TransactionHistory (ReferenceOrderID)  
    ON TransactionsPS1 (TransactionDate);  
GO  

K.K. 建立篩選的索引Creating a filtered index

下列範例會對 AdventureWorks2012AdventureWorks2012 資料庫中的 Production.BillOfMaterials 資料表建立篩選的索引。The following example creates a filtered index on the Production.BillOfMaterials table in the AdventureWorks2012AdventureWorks2012 database. 篩選述詞可以包含在已篩選之索引中不是索引鍵資料行的資料行。The filter predicate can include columns that are not key columns in the filtered index. 此範例中的述詞只會選取 EndDate 不是 NULL 的資料列。The predicate in this example selects only the rows where EndDate is non-NULL.

CREATE NONCLUSTERED INDEX "FIBillOfMaterialsWithEndDate"  
    ON Production.BillOfMaterials (ComponentID, StartDate)  
    WHERE EndDate IS NOT NULL;  

L.L. 建立壓縮的索引Create a compressed index

下列範例會使用資料列壓縮,在非分割區資料表上建立索引。The following example creates an index on a nonpartitioned table by using row compression.

CREATE NONCLUSTERED INDEX IX_INDEX_1   
    ON T1 (C2)  
WITH ( DATA_COMPRESSION = ROW ) ;   
GO  

下列範例會在索引的所有分割區上使用資料列壓縮,以便在分割區資料表上建立索引。The following example creates an index on a partitioned table by using row compression on all partitions of the index.

CREATE CLUSTERED INDEX IX_PartTab2Col1  
ON PartitionTable1 (Col1)  
WITH ( DATA_COMPRESSION = ROW ) ;  
GO  

下列範例會在分割區資料表上建立索引,其方式是在索引的分割區 1 上使用頁面壓縮,並在索引的分割區 24 上使用資料列壓縮。The following example creates an index on a partitioned table by using page compression on partition 1 of the index and row compression on partitions 2 through 4 of the index.

CREATE CLUSTERED INDEX IX_PartTab2Col1  
ON PartitionTable1 (Col1)  
WITH (DATA_COMPRESSION = PAGE ON PARTITIONS(1),  
    DATA_COMPRESSION = ROW ON PARTITIONS (2 TO 4 ) ) ;  
GO  

範例: Azure SQL 資料倉儲Azure SQL Data Warehouse平行處理資料倉儲Parallel Data WarehouseExamples: Azure SQL 資料倉儲Azure SQL Data Warehouse and 平行處理資料倉儲Parallel Data Warehouse

M.M. 基本語法Basic syntax

CREATE INDEX IX_VendorID   
    ON ProductVendor (VendorID);  
CREATE INDEX IX_VendorID   
    ON dbo.ProductVendor (VendorID DESC, Name ASC, Address DESC);  
CREATE INDEX IX_VendorID   
    ON Purchasing..ProductVendor (VendorID);  

N.N. 目前資料庫中的資料表上建立非叢集索引Create a non-clustered index on a table in the current database

下列範例會建立非叢集索引上VendorID資料行ProductVendor資料表。The following example creates a non-clustered index on the VendorID column of the ProductVendor table.

CREATE INDEX IX_ProductVendor_VendorID   
    ON ProductVendor (VendorID);   

O.O. 在另一個資料庫中的資料表上建立叢集的索引Create a clustered index on a table in another database

下列範例會建立非叢集索引上VendorID資料行ProductVendor資料表中Purchasing資料庫。The following example creates a non-clustered index on the VendorID column of the ProductVendor table in the Purchasing database.

CREATE CLUSTERED INDEX IX_ProductVendor_VendorID   
    ON Purchasing..ProductVendor (VendorID);   

P.P. 資料行加入索引Add a column to an index

下列範例會建立索引 IX_FF 含有 dbo 的兩個資料行。FactFinance 資料表。The following example creates index IX_FF with two columns from the dbo.FactFinance table. 下一個陳述式示範重建該索引具有相同名稱和一個詳細的資料行。The next statement demonstrates rebuilding that index with the same name and one more column.

CREATE INDEX IX_FF ON dbo.FactFinance (  
    FinanceKey ASC, DateKey ASC );  

--Rebuild and add the OrganizationKey  
CREATE INDEX IX_FF ON dbo.FactFinance (  
    FinanceKey, DateKey, OrganizationKey DESC)  
WITH ( DROP_EXISTING = ON );  

另請參閱See Also

ALTER INDEX (Transact-SQL) ALTER INDEX (Transact-SQL)
CREATE PARTITION FUNCTION (Transact-SQL) CREATE PARTITION FUNCTION (Transact-SQL)
CREATE PARTITION SCHEME (Transact-SQL) CREATE PARTITION SCHEME (Transact-SQL)
建立空間索引 (TRANSACT-SQL ) CREATE SPATIAL INDEX (Transact-SQL)
CREATE STATISTICS (Transact-SQL) CREATE STATISTICS (Transact-SQL)
CREATE TABLE (Transact-SQL) CREATE TABLE (Transact-SQL)
建立 XML 索引 (TRANSACT-SQL ) CREATE XML INDEX (Transact-SQL)
資料類型 (Transact-SQL) Data Types (Transact-SQL)
DBCC SHOW_STATISTICS (Transact-SQL) DBCC SHOW_STATISTICS (Transact-SQL)
DROP INDEX (TRANSACT-SQL ) DROP INDEX (Transact-SQL)
XML 索引 (SQL Server) XML Indexes (SQL Server)
sys.indexes (Transact-SQL) sys.indexes (Transact-SQL)
sys.index_columns (Transact-SQL) sys.index_columns (Transact-SQL)
sys.xml_indexes (TRANSACT-SQL ) sys.xml_indexes (Transact-SQL)
EVENTDATA (Transact-SQL)EVENTDATA (Transact-SQL)