如何使用mysql query / command从mysql数据库中删除所有视图?

时间:2012-01-13 10:08:37

标签: mysql database views

我需要从mysql数据库中删除所有视图。我怎么能用查询呢?

有人可以帮我吗?

4 个答案:

答案 0 :(得分:15)

我一直在使用这个:

/* DROP ALL VIEWS */

SET @views = NULL;
SELECT GROUP_CONCAT(table_schema, '.', table_name) INTO @views
 FROM information_schema.views 
 WHERE table_schema = @database_name; -- Your DB name here 

SET @views = IFNULL(CONCAT('DROP VIEW ', @views), 'SELECT "No Views"');
PREPARE stmt FROM @views;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:6)

引自MySQL Reference Manual

DROP VIEW [IF EXISTS]
    view_name [, view_name] ...
    [RESTRICT | CASCADE]

DROP VIEW删除一个或多个视图。您必须拥有每个视图的DROP权限。如果参数列表中指定的任何视图不存在,MySQL将返回一个错误,指出它无法删除哪些不存在的视图,但它也会丢弃列表中存在的所有视图。

IF EXISTS子句可防止对不存在的视图发生错误。给出此子句时,将为每个不存在的视图生成NOTE。请参阅第12.7.5.41节“显示警告语法”

RESTRICTCASCADE,如果给定,将被解析并被忽略。

答案 2 :(得分:2)

尝试这个未经测试的代码

DECLARE VIEW_NAME VARCHAR(31); 
DECLARE VIEW_NAMES CURSOR 
FOR 
SELECT table_name 
FROM information_schema.views; 
WHERE table_schema = 'DB_Name'
OPEN VIEW_NAMES; 
REPEAT 
FETCH VIEW_NAMES INTO VIEW_NAME; 
DROP VIEW VIEW_NAME     
UNTIL done END REPEAT; 
CLOSE VIEW_NAMES; 
END;

答案 3 :(得分:-1)

这是一个可以做你想做的Ruby方法:

# @param [Array] databases, e.g. ['db1', 'db2']
  def drop_all_views(databases)
    views = ActiveRecord::Base.connection.execute("SELECT CONCAT(TABLE_SCHEMA,'.',TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_TYPE = 'VIEW' AND TABLE_SCHEMA IN('#{databases.join("', '")}');")

    views = views.to_a.flatten

    # Then drop all of those views from their respective databases
    views.each do |v|
      ActiveRecord::Base.connection.execute("DROP VIEW IF EXISTS #{v};")
    end
  end