我有一个名为tableExists的函数。它可用于检查表的存在。我想在数据库升级脚本中使用它。我可以使用这样的函数:
select myDb.tableExists('myDb', 'someTable') as cnt into @exists;
看到这样的结果:
mysql> select @exists;
+---------+
| @exists |
+---------+
| 1 |
+---------+
现在,我想在If语句中使用它,然后是create table语句。但是,我遇到问题。以下是我要测试的内容:
mysql> IF (@exists = 1) THEN
-> select 'exists'
-> END IF;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
right syntax to use near 'IF (@exists = 1) THEN
select 'exists'
END IF' at line 1
我在这里缺少什么?这应该很简单。
答案 0 :(得分:3)
您只能在存储过程中使用IF
。
有效的select语句为:
SELECT CASE (@exists) WHEN 1 THEN 'exists' END as DoesItExist
如果您将案例用作存储过程中的独立元素,则无论如何都需要以end case
结束。
答案 1 :(得分:2)
为什么不在IF NOT EXISTS
查询中使用CREATE TABLE
,并省去所有这些麻烦:
CREATE TABLE new_table IF NOT EXISTS
... {table definition}
如果表已经存在,则不会发生任何事情。