我正在使用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行语法错误。
所以我想知道是否有人会更好地了解如何解决这个问题,或者如何解决这个问题。
答案 0 :(得分:3)
添加来自favaretto的代码,如果你有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
答案 1 :(得分:1)
您必须查询information_schema
数据库。在MySQL Forums上找到了这个答案:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename';
答案 2 :(得分: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;
答案 3 :(得分: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。