x

Can I create an index or constraint on a table variable?

Site seeder question: I am using a table variable in one of my queries:

DECLARE @intermediateData TABLE (
  ID        INT IDENTITY (1,1),
  KeyData   VARCHAR (255),
  ValueData VARCHAR (255));

Is it possible for me to create an index on the ID column?

more ▼

asked Oct 13, 2009 at 09:35 AM in Default

Matt Whitfield gravatar image

Matt Whitfield ♦♦
29.4k 61 65 87

(comments are locked)
10|1200 characters needed characters left

2 answers: sort voted first

You can create a primary key when you define the table variable, but you can't create an index on that column.

more ▼

answered Oct 13, 2009 at 10:03 AM

Grant Fritchey gravatar image

Grant Fritchey ♦♦
101k 19 21 74

(comments are locked)
10|1200 characters needed characters left

I'm just adding this because I was hoping for some syntax examples. A clustered primary key would be as follows:

DECLARE @intermediateData TABLE (
  ID        INT IDENTITY (1,1) PRIMARY KEY CLUSTERED,
  KeyData   VARCHAR (255),
  ValueData VARCHAR (255));

A unique constraint can also be defined through the following:

DECLARE @intermediateData TABLE (  ID INT IDENTITY (1,1),  KeyData VARCHAR (255),  ValueData VARCHAR (255)  UNIQUE (KeyData, ValueData)); 
more ▼

answered Oct 13, 2009 at 01:50 PM

Matt Whitfield gravatar image

Matt Whitfield ♦♦
29.4k 61 65 87

Sorry, I just answered it. I didn't think about the purpose of the question itself.
Oct 13, 2009 at 02:50 PM Grant Fritchey ♦♦
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x130
x22

asked: Oct 13, 2009 at 09:35 AM

Seen: 5502 times

Last Updated: Oct 13, 2009 at 09:35 AM