How do you ADD and DROP columns in a single ALTER TABLE

squeezy picture squeezy · Apr 13, 2013 · Viewed 31.3k times · Source

I tried the following but I got a syntax error

ALTER TABLE Grades ( 
DROP COLUMN (Student_FamilyName, Student_Name),
ADD Student_id INT );

Is it possible to perform a DROP and an ADD in the same ALTER TABLE statement?

Answer

Conrad Frix picture Conrad Frix · Apr 13, 2013

If you look at the ALTER TABLE SYTAX

you'll see this

ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name 
{ 
    ALTER COLUMN column_name 
    { 
        [ type_schema_name. ] type_name [ ( { precision [ , scale ] 
            | max | xml_schema_collection } ) ] 
        [ COLLATE collation_name ] 
        [ NULL | NOT NULL ] [ SPARSE ]

    | {ADD | DROP } 
        { ROWGUIDCOL | PERSISTED | NOT FOR REPLICATION | SPARSE }
    } 
        | [ WITH { CHECK | NOCHECK } ]

    | ADD 
    { 
        <column_definition>
      | <computed_column_definition>
      | <table_constraint> 
      | <column_set_definition> 
    } [ ,...n ]

    | DROP 
     {
         [ CONSTRAINT ] 
         { 
              constraint_name 
              [ WITH 
               ( <drop_clustered_constraint_option> [ ,...n ] ) 
              ] 
          } [ ,...n ]
          | COLUMN 
          {
              column_name 
          } [ ,...n ]
     } [ ,...n ]

This can be reduced to

ALTER TABLE { ALTER COLUMN column_name | ADD | DROP }

According to Transact-SQL Syntax Conventions (Transact-SQL) the | (vertical bar)

Separates syntax items enclosed in brackets or braces. You can use only one of the items.

So you can't Alter, Drop or Add in a single statement. You also have the parens and comma that won't work. So you'll need

ALTER TABLE Grades DROP COLUMN (Student_FamilyName, Student_Name);
ALTER TABLE Grades ADD  Student_id INT;

If you need them to be an atomic action you just need to wrap in transaction