如何使用存储过程删除mysql数据库中的所有视图?
作者:互联网
我希望我的mysql服务器删除数据库中的所有视图.我已经为存储过程创建了一个事件:
开始
DECLARE done INT DEFAULT FALSE;
DECLARE VIEW_NAME CHAR(255);
DECLARE VIEW_NAMES CURSOR FOR SELECT table_name FROM information_schema.views;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN VIEW_NAMES;
read_loop: LOOP
FETCH VIEW_NAMES INTO VIEW_NAME;
IF done THEN
LEAVE read_loop;
END IF;
DROP VIEW VIEW_NAME;
END LOOP;
CLOSE VIEW_NAMES;
结束
但是,此过程会产生以下错误:
Error Code: 1051. Unknown table ‘view_name’
我的猜测是我的fetch语句由于某种原因没有获取.所以我检查了select语句,它确实有一个结果集.任何有关如何解决错误或如何在mysql数据库中删除所有视图的想法?
解决方法:
您需要使用prepared statements来执行这些查询.构建字符串’DROP VIEW …’,然后使用预准备语句执行语句.
例如 –
...
read_loop: LOOP
FETCH VIEW_NAMES INTO VIEW_NAME;
IF done THEN
LEAVE read_loop;
END IF;
SET @query = CONCAT('DROP VIEW ', VIEW_NAME);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
...
另一个变种,没有打开光标:
SET @views = NULL;
SELECT GROUP_CONCAT(table_schema, '.', table_name) INTO @views
FROM information_schema.views
WHERE table_schema = 'database_name';
SET @views = CONCAT('DROP VIEW ', @views);
PREPARE stmt FROM @views;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
…根据需要修改WHERE条件.
标签:mysql,stored-procedures,sql-view 来源: https://codeday.me/bug/20190826/1725975.html