MySQL 的 SQL 脚本中的 If 条件
在顺序执行的sql脚本中,有没有一种方法可以引入IF THEN ELSE条件来控制查询执行的流程?
我碰巧遇到了这个 http://www.bennadel.com/blog/1340-MySQL-Does-Not-Support-IF-ELSE-Statements-In-General-SQL-Work-Flow.htm 这表明 IF THEN ELSE 在 sql 脚本中不起作用。
还有其他办法吗?
基本上,我想运行特定的“从表中选择 colName”命令并检查 colName 是否对应于特定值。如果是,请继续执行脚本的其余部分。否则,停止执行。
请指教。
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.htm
which says that the IF THEN ELSE will not work in a sql script.
Is there another way around?
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.
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我只是将 SQL 脚本包装在允许使用条件代码的过程中。如果您不想保留这些语句,则可以在完成后删除该过程。下面是一个示例:
如果您没有使用过过程,那么“delimiter”关键字可能需要一些解释。第一行将分隔符切换为“//”,以便我们可以在过程定义中包含分号,而无需 MySQL 尝试解释它们。创建过程后,我们将分隔符切换回“;”所以我们可以像往常一样执行语句。
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:
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.
经过一些研究后,我想我可能找到了解决这个问题的方法。我正在寻找一种方法来验证脚本是否已针对目标数据库执行。这主要用于我的数据库的版本控制。我创建了一个表来跟踪已执行的脚本,并希望脚本中的一些流程在执行之前首先检查该表。虽然我还没有完全解决问题,但我已经创建了一个简单的脚本,基本上可以满足我的需要,我只需要根据变量的值将 DDL 包装到选择中。
这是示例脚本,
我也认识到这是一个旧线程,但也许这会帮助那些尝试在像我这样的存储过程之外做这种事情的人。
After doing some research I think I may have found a way to work around this. I was looking for a way to verify if a script had already executed against a target database. This will be primarily for version control of my databases. I have a table created to keep track of the scripts that have been executed and wanted some flow inside my scripts to check that table first before execution. While I have not completely solved the problem yet I have created a simple script that basically does what I need, I just need to wrap the DDL into the selects based on the value of the variables.
Here is the example script
I also recognize this is an old thread but maybe this will help someone out there trying to do this kind of thing outside of a stored procedure like me.