MySql IF statement in query
I just finished picking up my jaw off the floor after learning that you can't use an IF statement in a query in MySql. How can anyone get anything done without an IF statement?!
What I'm trying to do is write a DML script that adds a constraint to a table, if it doesn't exist. Something like this:
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;
How would one do this in MySql?
Thanks in advance!
You can only run IF statements in stored procedures and functions.
http://dev.mysql.com/doc/refman/5.0/en/if-statement.html
If you are executing standard scripts, then IF statements only work with SELECT queries.
http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if
Procedural batch, but within the below, a proc is created and dropped after the operation completes.
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;
精彩评论