2017-06-13 1 views
1
私はこのコードを書いて、私はそれを実行するとき、それは私が

ないのはなぜ私の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;')); 
prepare stmt from @s1; 
execute stmt; 
deallocate prepare stmt; 
update foo set bar_id = baz_id; 
に私のコードを変更した場合、私は更新ステートメント

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; 

近くMySQLの構文に問題があると言う

それが動作します。 if文の中にupdate文が必要です。

私はこれをSPにすることはできません。

エラー:あなたの最初のコードブロックで

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 'update foo set bar_id = baz_id' at line 1

+1

エラーメッセージを読んでみてください。通常は何が間違っているのかを示します。 –

+0

エラーはちょうど私に正しい構文を使用するように頼みます。 –

+0

いいえ、慎重に見てください:**近所 'update foo set ** –

答えて

2

、あなたは 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を帯域外に追加し、必要に応じて更新を実行するだけです。

0

問題は、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 
関連する問題