Tuesday, May 3, 2011

Alter Table Add Column Syntax

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'."

From stackoverflow
  • 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]
    
  • 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.

    Örjan Jämte : "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)?

0 comments:

Post a Comment