Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: how to write an alter index statement to add a column to the unique index?

I have a UNIQUE, NON CLUSTERED index on a table that is currently using 4 columns for the index.

I want to create an alter script that can merely add another column to this index. The new column type is varchar.

The database is SQL Server 2005.

Thanks in advance.

like image 329
JL. Avatar asked Mar 19 '12 07:03

JL.


People also ask

How do I add a column to an existing index in SQL Server?

Expand the table in which the index belongs and then expand Indexes. Right-click the index that you want to modify and then click Properties. In the Index Properties dialog box, make the desired changes. For example, you can add or remove a column from the index key, or change the setting of an index option.

How do I add a column to an existing index?

Procedure. To add a column to an existing index: Issue the ALTER INDEX ADD COLUMN SQL statement when you add a column to a table. Commit the alter procedure.

How do I add a unique index in SQL?

Right-click the table on which you want to create a unique index and select Design. On the Table Designer menu, select Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box.

How do I make a column value unique in SQL Server?

Expand the "General" tab. Make sure you have the column you want to make unique selected in the "columns" box. Change the "Type" box to "Unique Key". Click "Close".


1 Answers

You cannot alter an index - all you can do is

  1. drop the old index (DROP INDEX (indexname) ON (tablename))

  2. re-create the new index with the additional column in it:

       CREATE UNIQUE NONCLUSTERED INDEX (indexname)    ON dbo.YourTableName(columns to include) 

The ALTER INDEX statement in SQL Server (see docs) is available to alter certain properties (storage properties etc.) of an existing index, but it doesn't allow changes to the columns that make up the index.

like image 67
marc_s Avatar answered Sep 21 '22 12:09

marc_s