adding column to all tables in a mysql database (unknown table names)

前端 未结 4 828
予麋鹿
予麋鹿 2021-02-08 08:49

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

4条回答
  •  长情又很酷
    2021-02-08 09:18

    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 ;
    

提交回复
热议问题