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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)