Skip to content
Advertisement

Use a variable or function in MYSQLs ALTER TABLE statement

In Mysql/MariaDB I like to set the comment of an existing column to a string containing the current date.

But I only get SQL syntax errors. I’ve tried so far:

SELECT @date := CONCAT('saved at', now());
ALTER TABLE table_name MODIFY 
    column_name <complete column definition> COMMENT @date;

Also not working:

ALTER TABLE table_name MODIFY
    column_name <complete column definition> COMMENT now();

Of course this works:

ALTER TABLE table_name MODIFY
    column_name <complete column definition> COMMENT 'saved at today';

Is this possible without an external script?

Advertisement

Answer

SET @sql := CONCAT ( 'ALTER TABLE {table_name} ',
                     'MODIFY {column_name} {complete column definition} ',
                     'COMMENT 'saved at ' , CURRENT_TIMESTAMP, ''' );
PREPARE stmt FROM @sql;
EXECUTE stmt;
DROP PREPARE stmt;

demo

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement