[英]How do I use an IF statement with an ALTER statement in MySQL?
I'm looking to add a column only if it does not already exist before. 我希望仅在以前不存在的情况下添加该列。 The motivation for this is that we can upgrade any version of a production instance to the latest version. 这样做的动机是我们可以将生产实例的任何版本升级到最新版本。
This is what I'm trying, but I keep getting a syntax error near the IF
statement: 这是我正在尝试的方法,但是在IF
语句附近不断出现语法错误:
use database_name
SELECT @rowcount:=COUNT(column_name)
FROM information_schema.columns
WHERE table_name = 'table_name'
AND column_name = 'column_2';
IF @rowcount < 1 THEN
ALTER TABLE table_name
ADD COLUMN column_2 VARCHAR(42) DEFAULT 'abcd',
END IF;
commit;
What am I doing wrong? 我究竟做错了什么?
You asked: 您询问:
How do I use an IF statement with an ALTER statement in MySQL? 如何在MySQL中将IF语句和ALTER语句一起使用?
You Can't Do That™. 您不能那样做™。 MySQL's DML and DDL aren't as well integrated as other makes and models of table server. MySQL的DML和DDL与其他品牌和型号的表服务器的集成度不高。
You can't put DML inside stuff like IF statements or transactions. 您不能将DML放入IF语句或事务之类的内容中。 If you need to do that sort of operation you'll have to use an application programming language to issue simpler SQL. 如果需要执行此类操作,则必须使用应用程序编程语言来发布更简单的SQL。
I think you should change 我认为你应该改变
IF @rowcount < 0 THEN ALTER TABLE table_name ADD COLUMN column_2 VARCHAR(42) DEFAULT 'abcd', END IF;
and check if table exist. 并检查表是否存在。
As @Ollie Jones mentions and from looking at Using an IF Statement in a MySQL SELECT query , it looks like it's not possible to use if statements outside of sprocs or functions. 正如@Ollie Jones提到的那样,从在MySQL SELECT查询中使用IF语句开始 ,似乎无法在存储过程或函数之外使用if语句。
I followed the steps on http://www.cryer.co.uk/brian/mysql/howto_add_column_unless_exists.htm : 我按照http://www.cryer.co.uk/brian/mysql/howto_add_column_unless_exists.htm上的步骤进行操作:
Alternatively, as @Ollie Jones mentions, you can do it at an application level, but I'm using .sql
files in my case. 另外,就像@Ollie Jones提到的那样,您可以在应用程序级别执行此操作,但是我使用的是.sql
文件。 It also saves on making multiple calls to the DB vs. having it done at the server level. 与在服务器级别完成多次调用相比,它还节省了对数据库的多次调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.