1

Just wanted to check, if we will be able to create indexes on User-defined Table variables. I know that we can create PK on an UDT. Does it imply that PK creates an (clustered) index internally? If an index is possible on a column on UDT, where does the indexed data get stored?

1
  • Do you mean for User Defined Table types, or for Table variables? (It's not going to change the answer much, it's just that the right MSDN pages to link to are different :-|) Commented Feb 23, 2011 at 13:39

3 Answers 3

4

To define an index on a table variable use a primary key or unique constraint. You can nominate one as clustered.

  • If you need an index on a non-unique field, simply add the unique key to the end of the index column list, to make it unique.

  • If the table variable has not got a unique field, add a dummy unique field using an identity column.

Something like this:

declare @t table (
    dummy identity primary key nonclustered,
    val1 nvarchar(50),
    val2 nvarchar(50),
    unique clustered (val1, dummy)
) 

Now you have a table variable with a clustered index on non-unique field val1.

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

Comments

3

With table variables, you can define primary key and unique constraints, but you are unable to define any clustering behaviour. The indexes for these are stored alongside the actual data in the table variable - hopefully in memory within tempdb, but if necessary, spilled to disk, if memory pressure is high.

You're unable to define arbitrary indexes on such tables.

Comments

0

You can however define whatever indexes you want on temp tables.

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.