Answer

问题及解答

查看数据库 Company 中所有表使用的存储引擎是什么.

Posted by haifeng on 2021-12-18 09:38:28 last update 2021-12-18 09:54:31 | Edit | Answers (1)

这部分的信息存储在 information_schema 数据库的表 tables 中.

 

mysql> SELECT table_catalog, table_schema, table_name, engine
    -> FROM information_schema.tables
    -> WHERE table_schema='Company';
+---------------+--------------+---------------+--------+
| table_catalog | table_schema | table_name    | engine |
+---------------+--------------+---------------+--------+
| def           | company      | department    | MyISAM |
| def           | company      | dependent     | MyISAM |
| def           | company      | dept_location | MyISAM |
| def           | company      | employee      | InnoDB |
| def           | company      | project       | MyISAM |
| def           | company      | works_on      | MyISAM |
+---------------+--------------+---------------+--------+
6 rows in set (0.00 sec)

 

写一个存储过程, 将Company数据库中所有不是 InnoDB 引擎的数据表都改为 InnoDB 引擎.

 

1

Posted by haifeng on 2021-12-19 12:55:18

 SELECT table_name  FROM information_schema.tables WHERE table_schema='Company' and engine='MyISAM';

可以返回 Company 数据库中存储引擎是 MyISAM 的诸表. 将此作为此查询, 使用 IN 操作符, 判断 Company 中的表是否属于该集合, 如果是, 则修改存储引擎为 InnoDB.

修改引擎的语句为:

ALTER TABLE tblname ENGINE=InnoDB;

 

现在要写一个存储过程, 过程名和参数不妨写为  changeEngine(DBname), 其中 DBname 为数据库的名字.

delimiter $$

CREATE PROCEDURE changeEngine(IN DBname VARCHAR(20))
BEGIN

DECLARE tblname VARCHAR(20); 
DECLARE Not_Found CONDITION FOR SQLSTATE '02000';
DECLARE TblCursor CURSOR FOR SELECT table_name  FROM information_schema.tables WHERE table_schema=DBname and engine='MyISAM';

OPEN TblCursor;
    myLoop: LOOP
        FETCH FROM TblCursor INTO tblname;
        IF Not_Found THEN LEAVE myLoop; END IF;
        ALTER TABLE tblname ENGINE=InnoDB;
    END LOOP;
CLOSE TblCursor;
END$$

 

注意这里 ALTER TABLE tblname ENGINE=InnoDB; 并没有将 tblname 替换为TblCursor所指的值. 因此仍需修改.


正确的写法是

 

DROP PROCEDURE changeEngine;
delimiter $$
CREATE PROCEDURE changeEngine(IN DBname VARCHAR(20))
BEGIN
 
DECLARE tblname VARCHAR(20); 
DECLARE done BOOLEAN DEFAULT 1;
 
DECLARE TblCursor CURSOR FOR SELECT table_name  FROM information_schema.tables WHERE table_schema=DBname and engine='MyISAM';
DECLARE exit HANDLER FOR SQLSTATE '02000' SET done=0;
 
OPEN TblCursor;
    WHILE done
    DO
        FETCH FROM TblCursor INTO tblname;
SET @sql=CONCAT( 'ALTER TABLE ', tblname, ' ENGINE=InnoDB;' );
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
    END WHILE;
CLOSE TblCursor;
END$$