sql server 2000 TSQL: creating index on table variable

时光毁灭记忆、已成空白 提交于 2019-12-08 04:37:35

问题


Is the following possible? I am unable to do so. Do I have to have a permanent table to create index?

declare @Beatles table
    (
        LastName varchar(20) ,      
        FirstName varchar(20) 
    )

CREATE CLUSTERED INDEX Index_Name_Clstd ON @Beatles(LastName)

回答1:


Not on a table variable, but on a temp table see this http://www.sqlteam.com/article/optimizing-performance-indexes-on-temp-tables




回答2:


No, you cannot create indices on a table variable - see this article here and this posting here comparing local, global temporary tables to table variables.

Restrictions

You cannot create a non-clustered index on a table variable, unless the index is a side effect of a PRIMARY KEY or UNIQUE constraint on the table (SQL Server enforces any UNIQUE or PRIMARY KEY constraints using an index).




回答3:


According to this post - YES you can. The following declaration will generate 2 indexes:

DECLARE @Users TABLE
(
    UserID  INT PRIMARY KEY,
    UserName VARCHAR(50),
    FirstName VARCHAR(50),
    UNIQUE (UserName,UserID)
)

The first index will be clustered, and will include the primary key. The second index will be non clustered and will include the the columns listed in the unique constraint. Here is another post, showing how to force the query optimizer to use the indexes generated dynamically, because it will tend to ignore them (the indexes will be generated after the execution plan is evaluated)



来源:https://stackoverflow.com/questions/1923438/sql-server-2000-tsql-creating-index-on-table-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!