Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created November 26, 2012 20:40
Show Gist options
  • Save Rican7/4150476 to your computer and use it in GitHub Desktop.
Save Rican7/4150476 to your computer and use it in GitHub Desktop.
MySQL: Change all given columns of a table from "int"'s to "timestamps"
DROP PROCEDURE IF EXISTS changeIntToTimestamps;
DELIMITER //
CREATE PROCEDURE changeIntToTimestamps(
myschema VARCHAR(255),
colname VARCHAR(255),
autoUpdate BOOL
)
BEGIN
DECLARE mytable VARCHAR(255);
DECLARE col VARCHAR(255);
DECLARE dtype VARCHAR(255);
DECLARE mysql VARCHAR(255);
DECLARE done INT default false;
DECLARE allcols cursor for
select
c.TABLE_NAME,
c.COLUMN_NAME,
c.DATA_TYPE
from
INFORMATION_SCHEMA.COLUMNS c
inner join INFORMATION_SCHEMA.TABLES t on
c.TABLE_CATALOG = t.TABLE_CATALOG
and c.TABLE_SCHEMA = t.TABLE_SCHEMA
and c.TABLE_NAME = t.TABLE_NAME
where
c.DATA_TYPE like '%int%'
and c.column_name like colname
and c.TABLE_SCHEMA = myschema
;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;
open allcols;
fetch_loop: LOOP
fetch next from allcols into mytable, col, dtype;
if done then
LEAVE fetch_loop;
end if;
set @mysql = CONCAT('alter table ', myschema, '.', mytable, ' CHANGE `', col, '` `', col, '` TIMESTAMP');
if autoUpdate then
set @mysql = CONCAT(@mysql, ' ON UPDATE CURRENT_TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP');
else
set @mysql = CONCAT(@mysql, ' NULL');
end if;
PREPARE statement from @mysql;
SET @myschema = myschema;
SET @mytable = mytable;
SET @col = col;
execute statement;
DEALLOCATE PREPARE statement;
end LOOP;
close allcols;
SELECT * FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = myschema AND `COLUMN_NAME` LIKE colname;
END
//
DELIMITER ;
call changeIntToTimestamps( DATABASE(), 'created_on', false );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment