2011-03-26 108 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