Command to drop all columns in a database that have prefix test_ to run

后端 未结 4 492
一整个雨季
一整个雨季 2020-12-16 08:08

How I can run a command in phpMyAdmin which will drop all columns in a database that have the prefix test_.

4条回答
  •  温柔的废话
    2020-12-16 08:40

    If you actually want to drop the columns from your schema, you will need to generate the necessary SQL commands dynamically from MySQL's information schema tables. Whilst it is possible to do that within a MySQL stored procedure using SQL prepared statements, which I demonstrate below, you may well find it easier to implement/understand in your preferred development language (which you do not mention in your question):

    DELIMITER ;;
    
    CREATE PROCEDURE dropMatchingColumns(IN pattern VARCHAR(64))
    BEGIN
      DECLARE done INT DEFAULT FALSE;
      DECLARE cur CURSOR FOR
        SELECT   CONCAT(
                     'ALTER TABLE `', REPLACE( TABLE_NAME, '`', '``'), '` ',
                   GROUP_CONCAT(
                     'DROP COLUMN `', REPLACE(COLUMN_NAME, '`', '``'), '`'
                   )
                 )
        FROM     INFORMATION_SCHEMA.COLUMNS
        WHERE    COLUMN_NAME LIKE pattern AND TABLE_SCHEMA = DATABASE()
        GROUP BY TABLE_NAME
      ;
      DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
      OPEN cur;
    
      read_loop: LOOP
        FETCH cur INTO @sql;
        IF done THEN
          LEAVE read_loop;
        END IF;
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
      END LOOP;
    
      CLOSE cur;
    END;;
    
    DELIMITER ;
    

    With this procedure defined, one need only CALL dropMatchingColumns('test\_%'); in order to drop all the columns prefixed with test_ from the current database.

提交回复
热议问题