将参数传递给MySQL脚本 [英] Pass parameters to MySQL script
本文介绍了将参数传递给MySQL脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为query1.sql
的MySQL脚本文件,其中包含:
I have a MySQL script file named query1.sql
which contains:
select * FROM $(tblName) LIMIT 10;
我在MySQL控制台中,如何将参数传递给脚本?这不会转发变量:
I am in MySQL console, how do I pass the parameter to the script? This does not forward the variable:
mysql> \. query1.sql -v tblName=Users
推荐答案
您可以使用用户变量以实现您描述的行为.在将变量用作模式标识符而不是数据值时,必须使用准备好的语句,以便可以动态地构成查询.
You can use user variables to achieve the behaviour you describe. As you use the variable as a schema identifier, not a data value, you'll have to use a prepared statement so you can compose the query dynamically.
query1.sql
:
SET @query = CONCAT('Select * FROM ', @tblName, ' LIMIT 10');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
调用为
mysql> SET @tblName = 'Users'; \. query1.sql
这篇关于将参数传递给MySQL脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文