【问题标题】:Why doesn't my mysql code work为什么我的mysql代码不起作用
【发布时间】:2017-06-13 23:40:14
【问题描述】:

我写了这段代码,当我执行它时,它说我在更新语句附近的 mysql 语法有问题

set @s1 = (select if ((select count(*) from information_schema.columns where table_name='foo' and column_name='bar_id') > 0,
                      'select 1',
                      'alter table foo add column bar_id bigint; update foo set bar_id = baz_id;'));
prepare stmt from @s1;
execute stmt;
deallocate prepare stmt;

如果我将代码更改为

set @s1 = (select if ((select count(*) from information_schema.columns where table_name='foo' and column_name='bar_id') > 0,
                      'select 1',
                      'alter table foo add column bar_id bigint;'));
prepare stmt from @s1;
execute stmt;
deallocate prepare stmt;
update foo set bar_id = baz_id;

然后就可以了。但我想要 if 条件中的更新语句。

我不能把它变成 SP。

错误:

ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“update foo set bar_id = baz_id”附近使用正确的语法

【问题讨论】:

  • 尝试阅读错误信息。它通常会说明问题所在。
  • 错误只是要求我使用正确的语法。
  • 不,仔细看:near 'update foo set

标签: mysql


【解决方案1】:

在您的第一个代码块中,您尝试准备一个包含两个 SQL 语句的字符串。不幸的是,MySQL prepare / execute cannot have multiple statements

如果您不能使用 SP,我想我建议您这样做:

set @s1 = (select if ((select count(*) from information_schema.columns where table_name='foo' and column_name='bar_id') > 0,
                      'select 1',
                      concat('alter table foo add column bar_id bigint default ', baz_id)));

prepare stmt from @s1;
execute stmt;
deallocate prepare stmt;

alter table foo alter column bar_id drop default;

但是,老实说,我建议您尽量减少 DDL 更改,因为这些更改可能具有不可预测的运行时行为。在这种情况下,这意味着在带外添加 foo.bar_id 并根据需要执行更新。

【讨论】:

    【解决方案2】:

    问题是 MySQL 的预处理语句不支持多语句。

    如果您想编写数据库结构更新的脚本,最简单的方法是使用没有动态 SQL 的过程(您可能还想在进行更改时检查 table_schema)。

    create procedure sp_fix_structure()
    begin
    
    declare v_cnt int;
    
    select count(*) into v_cnt
    from information_schema.columns
    where table_schema=database() and table_name='foo' and column_name='bar_id';
    
    if (v_cnt=0) then
      alter table foo add column bar_id bigint;
      update foo set bar_id = baz_id;
    end if;
    
    end
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2014-01-23
      • 2013-08-06
      • 2016-01-23
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多