1

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)
2
  • So, if I want to optimize in terms of table variables then I could just create index in the table definition like as follows?? declare @Beatles table (LastName varchar(20) NOT NULL PRIMARY KEY CLUSTERED, FirstName varchar(20) NOT NULL UNIQUE NONCLUSTERED); select lastname from @Beatles Commented Dec 17, 2009 at 19:26
  • You'd have to do it on a temp table or a regular table. Commented Dec 18, 2009 at 18:11

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

that works for temp tables - but not for table variables!
marc i misread it and was changing it when you replied..god this site is awfully fast!
@Jonh: <hehe> you gotta think and type at approx. the speed of light here!
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).

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.