Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set and index on two columns of T-SQL declared table variable?

Using SQL Server 2008 R2

Consider a declared table variable like:

DECLARE @t TABLE (PK int IDENTITY(1,1) PRIMARY KEY CLUSTERED, Col1 int, Col2 int)

How do I CREATE NONCLUSTERED INDEX of any name ON @t including (Con1 ASC, Col2 ASC)

The index should not be limited to unique values.

For some reason I do not manage to figure this out...

like image 470
elarrow Avatar asked Jul 05 '12 06:07

elarrow


People also ask

How do I create an index on two columns in SQL Server?

SQL Server CREATE INDEX statement In this syntax: First, specify the name of the index after the CREATE NONCLUSTERED INDEX clause. Note that the NONCLUSTERED keyword is optional. Second, specify the table name on which you want to create the index and a list of columns of that table as the index key columns.

Is it possible to create an index on two columns in SQL?

CREATE INDEX [index name] ON [Table name]([column1, column2, column3,...]); Multicolumn indexes can: be created on up to 32 columns. be used for partial indexing.

Can you put an index on a table variable in SQL Server?

Short answer: Yes. A more detailed answer is below. Traditional tables in SQL Server can either have a clustered index or are structured as heaps. Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique.

How do you DECLARE a table variable in SQL?

To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.


1 Answers

You can create a non clustered index as follows.

DECLARE @t TABLE (
  PK   INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Col1 INT,
  Col2 INT,
  UNIQUE (Col1, Col2, PK)) 

If the intention is that Col1, Col2 are unique themselves then remove PK from the column list.

Though it appears at face value as though this has added an additional column in (PK) the index structure will be the same as creating a non unique index on just Col1, Col2 on a #temp table.

CREATE TABLE #T  (
  PK   INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Col1 INT,
  Col2 INT) 

/*PK added in to end of key anyway*/  
CREATE NONCLUSTERED INDEX ix ON #T(Col1, Col2)

for a non unique non clustered index SQL Server always adds the CI key to the NCI key implicitly anyway. This just shows it explicitly.

See Kalen Delaney More About Nonclustered Index Keys

like image 107
Martin Smith Avatar answered Sep 20 '22 20:09

Martin Smith