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?

asked Feb 23, 2011 at 13:14
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.

answered Dec 16, 2013 at 13:09

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.

answered Feb 23, 2011 at 15:34

Comments

0

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

answered Feb 25, 2011 at 22:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.