1

I am getting error for the below code

ALTER TABLE ADM_Roles ALTER COLUMN RoleID int IDENTITY (1, 1)

Incorrect syntax near the keyword IDENTITY.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
Ram
  • 11
  • 1
  • 1
  • 2
  • [Are you on an edition that supports partitioning?](http://stackoverflow.com/questions/6084572/how-to-set-auto-increment-after-creating-a-table-without-any-data-loss/6086661#6086661) – Martin Smith Sep 09 '11 at 11:43

3 Answers3

6

You cannot change an existing column into an IDENTITY column - you will need to add a new column that has the identity flag:

ALTER TABLE dbo.ADM_Roles 
 ADD NewRoleID INT IDENTITY (1, 1)

If you need to, you can later on drop the old column and rename the new column to the old name:

ALTER TABLE dbo.ADM_Roles DROP COLUMN RoleID

EXEC sp_rename @objName = 'dbo.ADM_Roles.NewRoleID', 
               @newName = 'RoleID', 
               @objType = 'COLUMN'
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

From the MSDN

You can't alter the existing columns for identity.

You have 2 options,

  1. Create a new table with identity & drop the existing table

  2. Create a new column with identity & drop the existing column But take special care when these columns have any constraints / relations.

Example approach:

  • In this approach you can’t retain the existing data values on the newly created identity column;
  • The identity column will hold the sequence of number

    Alter Table Names Add Id_new Int Identity(1,1)
    Go
    
    Alter Table Names Drop Column ID
    Go
    
    Exec sp_rename 'Names.Id_new', 'ID','Column'
    
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MiBu
  • 869
  • 8
  • 17
-1

you have to remove the word "int".

ALTER TABLE ADM_Roles ALTER COLUMN RoleId IDENTITY (1, 1);
JAiro
  • 5,914
  • 2
  • 22
  • 21