2011-03-26 107 views
0

我剛剛完成了在MySql中的查詢中不能使用IF語句之後從地板上摘下我的下巴。沒有IF語句,任何人都可以得到什麼?!查詢中的MySql IF語句

我想要做的是編寫一個DML腳本,如果它不存在,則向表添加約束。就像這樣:

if (select count(*) from information_schema.table_constraints 
    where constraint_name='fk_user_user_status') = 0 
then 
    alter table `user` 
     add constraint fk_user_user_status foreign key (status_id) 
      references user_status(id); 
end if; 

在MySql中如何做到這一點?

在此先感謝!

+0

相關:http://stackoverflow.com/questions/3919226/mysql-add-constraint-if-not-exists – viaclectic 2011-03-26 08:54:26

回答

2

程序批,但內部的下方,一個進程被創建並在操作完成後刪除。

delimiter $$ 

drop procedure if exists tmp_add_fk $$ 

create procedure tmp_add_fk() 
begin 
if (select count(*) from information_schema.table_constraints 
    where constraint_name='fk_user_user_status') = 0 
then 
    alter table `user` 
     add constraint fk_user_user_status foreign key (status_id) 
      references user_status(id); 
end if; 
end$$ 

delimiter ; 

call tmp_add_fk; 

drop procedure tmp_add_fk; 
+0

真棒!謝謝,理查德!我只是在考慮做同樣的事情。但有一個問題:那些$$和分隔符是什麼? – alekop 2011-03-27 23:29:28

+0

@alekop由於proc在一個語句中完成,您幾乎可以離開而不更改分隔符。但是它允許你有多語句過程(包含';'),否則它會在它看到';'時立即結束proc定義。例如'delimiter $$'改變了它,所以語句只停留在$$。 – RichardTheKiwi 2011-03-27 23:56:38

+0

明白了,謝謝!這隻在使用'mysql' shell時纔是必需的。 – alekop 2011-03-27 23:57:01