squeezy
squeezy

Reputation: 627

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

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?

Upvotes: 32

Views: 47858

Answers (3)

Randi Firmansyah
Randi Firmansyah

Reputation: 13

you can use this one:

ALTER TABLE Grades
  DROP Student_FamilyName, 
  DROP Student_Name,
  ADD Student_id INT;

and you can use before/after like this:

ALTER TABLE Grades
  DROP Student_FamilyName, 
  DROP Student_Name,
  ADD Student_id INT AFTER id;

Upvotes: 0

Klesun
Klesun

Reputation: 13683

In case your database is MySQL, you can do it this way:

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

Works in MySQL 5.5.5

Upvotes: 8

Conrad Frix
Conrad Frix

Reputation: 52655

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

Upvotes: 31

Related Questions