I need to add a primary key to a set of tables in a given database. I do not know how many tables there will be or what their specific names are. They will all be of the for dat
You can do the following to change the columns. This uses a cursor to iterate over the table names and does not use text files or anything. You have to create this as a stored proc as cursors cannot be used outside.
DELIMITER $$
USE `db_name`$$
DROP PROCEDURE IF EXISTS `alter_test_1`$$
CREATE DEFINER=`db_name`@`10.%` PROCEDURE `alter_test_1`()
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_table VARCHAR(100) DEFAULT "";
DECLARE stmt VARCHAR(500) DEFAULT "";
DECLARE column_cursor CURSOR FOR
SELECT * FROM `information_schema`.`tables` WHERE table_schema = 'db_name' AND table_name LIKE 'mytables_%';
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN column_cursor;
alter_tables: LOOP
FETCH column_cursor INTO v_table;
IF v_finished = 1 THEN
LEAVE alter_tables;
END IF;
SET @prepstmt = CONCAT('ALTER TABLE adtracker','.',v_table,' ADD COLUMN id INT AUTO_INCREMENT NOT NULL;');
PREPARE stmt FROM @prepstmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP alter_tables;
CLOSE column_cursor;
END$$
DELIMITER ;