Home > Database > Mysql Tutorial > Can I Create Indexes on SQL Server Table Variables?

Can I Create Indexes on SQL Server Table Variables?

Mary-Kate Olsen
Release: 2025-01-12 21:32:46
Original
969 people have browsed it

Can I Create Indexes on SQL Server Table Variables?

Index on SQL Server table variable

In SQL Server 2014 and later, it is possible to create indexes directly on table variables using inline syntax. For example:

<code class="language-sql">DECLARE @T TABLE (
  C1 INT INDEX IX1 CLUSTERED,
  C2 INT INDEX IX2 NONCLUSTERED,
  INDEX IX3 NONCLUSTERED(C1, C2),
);</code>
Copy after login

In contrast, in SQL Server 2000 to 2012, indexes cannot be explicitly created on table variables. However, implicit indexes can be created through constraint declarations.

Create an index for the Name column in SQL Server 2000

Consider the following table variable declaration:

<code class="language-sql">DECLARE @TEMPTABLE TABLE (
  [ID] [INT] NOT NULL PRIMARY KEY,
  [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
);</code>
Copy after login

Can I create an index on the Name column?

Yes, you can use the UNIQUE NONCLUSTERED constraint to create an index on the Name column. The syntax is as follows:

<code class="language-sql">DECLARE @TEMPTABLE TABLE (
  [ID] [INT] NOT NULL PRIMARY KEY,
  [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
  UNIQUE NONCLUSTERED ([Name], [ID]),
);</code>
Copy after login

Implementation of indexes on table variables

Traditional tables in SQL Server can be clustered indexes or heaps. In table variables, indexes are created implicitly only through constraints. This means that the types of indexes that can be created on table variables are limited.

The following table summarizes the different types of indexes and whether they can be created on table variables in SQL Server 2000 to 2012.

索引类型 表变量支持
唯一聚集索引
非唯一聚集索引
堆上的唯一非聚集索引
堆上的非唯一非聚集索引
聚集索引上的唯一非聚集索引
聚集索引上的非唯一非聚集索引

In the example provided, a non-unique non-clustered index on the Name column is simulated by creating a unique index on Name and ID. This is because SQL Server implicitly adds clustered index keys to non-unique index keys.

The above is the detailed content of Can I Create Indexes on SQL Server Table Variables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template