0

alter table if field is not already exist

ALTER TABLE `table`
 ADD( `abc` text NOT NULL,
  `xyz` tinyint(1) NOT NULL,
  );

if abc or xyz fields are already exist the can not be alter table

if it is possible ?

Matten
  • 17,365
  • 2
  • 42
  • 64

2 Answers2

2

You can use a SHOW COLUMNS beforehand and construct your query accordingly, adding only fields that are missing.

Example output of SHOW COLUMNS:

mysql> SHOW COLUMNS FROM City;
+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| Id         | int(11)  | NO   | PRI | NULL    | auto_increment |
| Name       | char(35) | NO   |     |         |                |
| Country    | char(3)  | NO   | UNI |         |                |
| District   | char(20) | YES  | MUL |         |                |
| Population | int(11)  | NO   |     | 0       |                |
+------------+----------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

I can't comment yet, so I post answer: try this link for detailed example. It queries information_schema.COLUMNS table for column information about database tables.

vadchen
  • 1,442
  • 1
  • 11
  • 14