如何使用存储过程删除mysql数据库中的所有视图?

时间:2012-10-23 10:17:55

标签: mysql stored-procedures sql-view

我希望我的mysql服务器删除数据库中的所有视图。我已经为存储过程创建了一个事件:

BEGIN

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;

END

但是,此过程会产生以下错误:

  

错误代码:1051。未知表'view_name'

我的猜测是我的fetch语句由于某种原因没有获取。所以我检查了select语句,它确实有一个结果集。任何关于如何解决错误或如何在mysql数据库中删除所有视图的想法?

1 个答案:

答案 0 :(得分:6)

您需要使用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条件。