151

I'm trying to programmatically add an identity column to a table Employees. Not sure what I'm doing wrong with my syntax.

ALTER TABLE Employees
  ADD COLUMN EmployeeID int NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
    PK_Employees PRIMARY KEY CLUSTERED 
    (
      EmployeeID
    ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
    ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

What am I doing wrong? I tried to export the script, but SQL Mgmt Studio does a whole Temp Table rename thing.

UPDATE: I think it is choking on the first statement with "Incorrect syntax near the keyword 'COLUMN'."

GEOCHET
  • 20,745
  • 15
  • 72
  • 98
BuddyJoe
  • 67,353
  • 112
  • 287
  • 456

4 Answers4

206

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
Eoin Campbell
  • 42,194
  • 17
  • 98
  • 153
Vikram
  • 6,807
  • 8
  • 49
  • 59
16

This is how Adding new column to Table

ALTER TABLE [tableName]
ADD ColumnName Datatype

E.g

ALTER TABLE [Emp]
ADD Sr_No Int

And If you want to make it auto incremented

ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
Chiragkumar Thakar
  • 3,426
  • 5
  • 35
  • 48
8

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;
Dzianis Yafimau
  • 1,864
  • 1
  • 26
  • 35
0

It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.

neouser99
  • 1,767
  • 1
  • 9
  • 22
  • 1
    "easier that altering the order" - Do you mean that it is possible (although it is more difficult) to alter the order of the columns without recreating the table (through a temp table)? – Örjan Jämte Sep 16 '09 at 11:41
  • 1
    In a relational database, you should never have a need for the ordinality of the columns so if you are trying to neatly order the columns, the question is why? If column ordinality was so important, why isn't there a trivial function to swap or fix ordinality of columns? The reason is it designed for ordinality to not matter. – Shiv Nov 12 '14 at 03:54