User Tools

Site Tools


software:mysql:altering_tables
no way to compare when less than two revisions

Differences

This shows you the differences between two versions of the page.


software:mysql:altering_tables [2020/09/25 19:56] (current) – created rodolico
Line 1: Line 1:
 +====== Altering Tables ======
  
 +===== Adding a column =====
 +
 +To add a column **if it does not exist** you can do a Prepare/Execute function as follows:
 +<code sql>
 +SET @dbname = DATABASE();
 +SET @tablename = "tableName";
 +SET @columnname = "colName";
 +SET @preparedStatement = (SELECT IF(
 +  (
 +    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
 +    WHERE
 +      (table_name = @tablename)
 +      AND (table_schema = @dbname)
 +      AND (column_name = @columnname)
 +  ) > 0,
 +  "SELECT 1",
 +  CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
 +));
 +PREPARE alterIfNotExists FROM @preparedStatement;
 +EXECUTE alterIfNotExists;
 +DEALLOCATE PREPARE alterIfNotExists;
 +</code>
 +
 +Other ways of doing this are available in the discussion at [[https://stackoverflow.com/questions/24571611/mysql-alter-table-if-column-not-exists]]
 +
 +===== Links =====
 +  * [[https://stackoverflow.com/questions/24571611/mysql-alter-table-if-column-not-exists]]
software/mysql/altering_tables.txt · Last modified: 2020/09/25 19:56 by rodolico