1

我正在使用 MySQL 5.0+,如果表不存在,我正在尝试执行大量命令。所以我想拥有:

if not exist table
then
10000 line query that creates and populates the table with a lot of entries.
end if

唯一的问题是我一直在搜索,到目前为止我发现 MySQL 不支持这样的功能。

目前我有:

IF NOT EXISTS `profiles`
THEN
    A LOT OF QUERIES;
END IF;

出于某种原因,它不断给我错误,说第 1 行的语法错误。

所以我想知道是否有人会碰巧对如何解决这个问题或如何解决这个问题有更好的想法。

4

4 回答 4

3

添加到来自 bfavaretto 的代码,如果您确实有 information_schema.tables,请尝试以下操作:

IF NOT EXISTS (SELECT * FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename')
do your big long create table stuff
于 2012-01-30T19:14:01.817 回答
0

你可以尝试类似的东西

CREATE PROCEDURE test()
BEGIN
  DECLARE tmp INT;
  DECLARE CONTINUE HANDLER FOR  1146  -- 1146 - table does not exist
  BEGIN
     -- A lot of queries
  END;
  SELECT 1 INTO tmp FROM profiles LIMIT 1; -- INTO just to prevent any output
END;
于 2012-01-30T19:07:28.940 回答
0

您必须查询information_schema数据库。在MySQL 论坛上找到了这个答案:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename';
于 2012-01-30T18:59:19.853 回答
0

您可以尝试以下方法:

select * from table1 where exists (select table_name from information_schema.tables where table_schema=database() and table_name = 'table1');

只有当 table1 存在于当前数据库中时,才会出现“select * from table1”。这是避免在不存在的表中查询信息的好方法,这会导致错误。您可以在存储过程之外运行它,并且需要将“where exists ...”附加到您的每个查询中。有关更多信息,请参阅http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

于 2014-07-09T17:10:12.100 回答