1
create table stud(
Student_Id int primary key,
Student_Name varchar(30),
Student_surname varchar(12),
Student_Initial varchar(10))

I had created a table stud. Now i want to add Identity to Student_Id column using alter query

alter table stud alter column student_Id int identity   

I get error as

Incorrect syntax near the keyword 'identity'.

user2864740
  • 60,010
  • 15
  • 145
  • 220

5 Answers5

3
ALTER TABLE MyTable
  ADD ID INT IDENTITY(1,1) NOT NULL
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
Oasis
  • 480
  • 3
  • 16
2

You cannot make an already existing column as an IDENTITY column. Either you drop and recreate the table with the column marked as IDENTITY', or drop the column and add a newIDENTITY` column.

shree.pat18
  • 21,449
  • 3
  • 43
  • 63
1

Syntax:

IDENTITY [ (seed , increment) ]

alter your table like as this:

create table stud( 
Student_Id int IDENTITY(1,1) primary key,
Student_Name varchar(30), 
Student_surname varchar(12), 
Student_Initial varchar(10));
Majid
  • 13,853
  • 15
  • 77
  • 113
Meysam PH
  • 9
  • 2
1

If Stud contains data, you could always make a shadow table, e.g. Stud2, which contains the Identity column, then run

ALTER TABLE dbo.stud SWITCH TO dbo.stud2

Then you can reseed Stud2, drop Stud, and rename Stud2 to Stud.

That way you can keep the data while dropping/recreating the table with Identity.

Allan S. Hansen
  • 4,013
  • 23
  • 25
0

you can use below query to set identity

CREATE TABLE [dbo].[stud](
    [Student_Id] [int] IDENTITY(1,1) NOT NULL,
    [Student_Name] [varchar](30) NULL,
    [Student_surname] [varchar](12) NULL,
    [Student_Initial] [varchar](10) NULL,
PRIMARY KEY CLUSTERED 
(
    [Student_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF GO

Amul Harad
  • 148
  • 4