Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase «««12345

Things You Didn't Know About Temp Tables and Table Variables Expand / Collapse
Author
Message
Posted Tuesday, September 23, 2008 11:46 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Wednesday, May 20, 2009 1:02 AM
Points: 23, Visits: 26
We can add constraints on table variable like primary key, unique key and chekc constraints etc.. for eg.:

DECLARE @MyTable TABLE
(
ProductID int primary key IDENTITY(1,1),
Price money CHECK(Price < 10.0)
)

We cannot create non clustered index on table variable also we cannot change the declaration of table variable once created i.e. we cannot alter the table variable.
Post #574905
Posted Wednesday, September 24, 2008 8:15 AM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Saturday, September 13, 2014 8:37 AM
Points: 1,140, Visits: 703
sandeep.pote (9/23/2008)
We can add constraints on table variable like primary key, unique key and chekc constraints etc ...

...

We cannot create non clustered index on table variable ...


Just to clarify this statement (again!):

Both PKs and UNIQUE constraints are backed by indexes. By default, UNIQUE constraints are backed by nonclustered indexes. So by creating one of these constraints, you are in fact creating a nonclustered index. Therefore, it's fair to say that you can create both clustered and nonclustered indexes on a table variable.

Need a non-unique index? No problem, just use an IDENTITY column as a "uniquifier"...

DECLARE @n TABLE 
(
x INT NOT NULL,
y INT IDENTITY(1,1) NOT NULL,
PRIMARY KEY(x,y)
)

The IDENTITY column will of course increase the row size, so if you do this and you won't be inserting more than ~64,000 rows, consider using SMALLINT rather than INT (you can seed the IDENTITY with -32,000 to give yourself more room).


--
Adam Machanic
SQL Server MVP
SQLblog.com: THE SQL Server Blog Spot on the Web
Post #575233
« Prev Topic | Next Topic »

Add to briefcase «««12345

Permissions Expand / Collapse