删除表列(如果存在)(SQLSTATE [42000]语法错误或访问冲突)

时间:2017-08-30 11:06:28

标签: mysql

我需要删除一个表格列,如果它存在,但我有一些问题..我不断收到此错误,我无法弄清楚原因

An error occurred when processing the migration:
  Error: SQLSTATE[42000]: Syntax error or access violation: 1064 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 (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'my_d' at line 1

这是我的查询

IF (EXISTS (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'my_db_Name' AND TABLE_NAME = 'my__table' AND COLUMN_NAME = 'currency_format'))
BEGIN
   ALTER TABLE 'my__table' DROP COLUMN currency_format;  
END

Phpmyadmin SQL控制台也报告错误 enter image description here

那么,该怎么做我能够执行这个查询? 谢谢!

3 个答案:

答案 0 :(得分:0)

尝试在ALTER TABLE中取消引用您的tablename

答案 1 :(得分:0)

您可以使用:

IF (SELECT 1=1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'my_db_Name' AND TABLE_NAME = 'my__table' AND COLUMN_NAME = 'currency_format') THEN
BEGIN
   ALTER TABLE my__table DROP COLUMN currency_format;  
END IF;

答案 2 :(得分:0)

我使用以下代码进行了解决方法,现在正在使用

set @exist_Check := (
select count(*) from information_schema.columns
where TABLE_NAME='my__table'
and COLUMN_NAME='currency_format'
and TABLE_SCHEMA='my_db_Name'
);
set @sqlstmt := if(@exist_Check>0,'alter table my__table drop column currency_format', 'select ''''') ;
prepare stmt from @sqlstmt ;
execute stmt ;