Come indicato in manual page, ALTER TABLE
richiede la definizione di tutti i nuovi attributi di tipo.
Tuttavia, c'è un modo per superare questo. È possibile utilizzare INFORMATION_SCHEMA
meta-data per ricostruire la query ALTER
desiderata. per esempio, se abbiamo semplice tabella:
mysql> DESCRIBE t;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| value | varchar(255) | NO | | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
poi siamo in grado di riprodurre la nostra dichiarazione alter con:
SELECT
CONCAT(
COLUMN_NAME,
' @new_type',
IF(IS_NULLABLE='NO', ' NOT NULL ', ' '),
EXTRA
) AS s
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA='test'
AND
TABLE_NAME='t'
il risultato sarebbe:
+--------------------------------------+
| s |
+--------------------------------------+
| id @new_type NOT NULL auto_increment |
| value @new_type NOT NULL |
+--------------------------------------+
Qui ho lasciato @new_type
per indicare che possiamo usare una variabile per questo (o addirittura sostituire il nostro nuovo tipo direttamente alla query).Con variabile che sarebbe:
Impostare le nostre variabili.
mysql> SET @new_type := 'VARCHAR(10)', @column_name := 'value';
Query OK, 0 rows affected (0.00 sec)
Preparare variabile per prepared statement (è lunga query, ma ho lasciato spiegazioni sopra):
SET @sql = (SELECT CONCAT('ALTER TABLE t CHANGE `',COLUMN_NAME, '` `', COLUMN_NAME, '` ', @new_type, IF(IS_NULLABLE='NO', ' NOT NULL ', ' '), EXTRA) AS s FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='test' AND TABLE_NAME='t' AND [email protected]_name);
Preparare dichiarazione:
mysql> prepare stmt from @sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
Infine, eseguirlo:
mysql> execute stmt;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
Poi avremo il nostro tipo di dati cambiato VARCHAR(10)
con il salvataggio di tutti i prescrittori di riposo:
mysql> DESCRIBE t;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| value | varchar(10) | NO | | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
fonte
2014-04-07 14:13:58
ho avuto che [Modifica richiede] (http://dev.mysql.com/doc/refman /5.1/en/alter-table.html) tutte le _column_definition_, penso che potrebbe avere un'altra sintassi per cambiare solo quello che vuoi. –