问题描述
在执行顺序执行的sql脚本中,是否有一种方法可以引入IF THEN ELSE条件来控制查询执行的流程?
In a sql script that does sequential execution, is there a way one can introduce an IF THEN ELSE conditional to control the flow of query execution?
进入此
表示
I happened to run into this http://www.bennadel.com/blog/1340-MySQL-Does-Not-Support-IF-ELSE-Statements-In-General-SQL-Work-Flow.htmwhich says that the IF THEN ELSE will not work in a sql script.
还有另外一种方法?
基本上,我想要运行特定的select colName from table命令,并检查colName是否对应于特定值。如果是,继续脚本的其余部分。否则,暂停执行。
Basically, I want to run a particular "select colName from table" command and check if colName corresponds to a particular value. If it does, proceed with the rest of the script. Else, halt execution.
请指教。
推荐答案
在一个过程中包装我的SQL脚本,其中允许条件代码。如果你不想留下声明,你可以在完成后删除该程序。例如:
I just wrap my SQL script in a procedure, where conditional code is allowed. If you'd rather not leave the statements lying around, you can drop the procedure when you're done. Here's an example:
delimiter //
create procedure insert_games()
begin
set @platform_id := (select id from platform where name = 'Nintendo DS');
-- Only insert rows if the platform was found
if @platform_id is not null then
insert into game(name, platform_id) values('New Super Mario Bros', @platform_id);
insert into game(name, platform_id) values('Mario Kart DS', @platform_id);
end if;
end;
//
delimiter ;
-- Execute the procedure
call insert_games();
-- Drop the procedure
drop procedure insert_games;
如果没有使用过程,delimiter关键字可能需要一些解释。第一行将定界符切换为//,以便我们可以在我们的过程定义中包含分号,而MySQL尝试解释它们。一旦创建过程,我们将分隔符切换回;所以我们可以照常执行语句。
If you haven't used procedures, the "delimiter" keyword might need some explanation. The first line switches the delimiter to "//" so that we can include semi-colons in our procedure definition without MySQL attempting to interpret them yet. Once the procedure has been created, we switch the delimiter back to ";" so we can execute statements as usual.
这篇关于如果在SQL脚本中为有条件的Mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!