MySQL script with parameters

2019-05-06 20:55发布

I want to create a deployment script, somehow emulate Oracle deployment scripts, where with &param you can use previously declared parameters. I need to call this script for different users on different databases automatically.

For example my script should be:

USE &param;
DROP TABLE IF EXISTS `TEST` ;
CREATE TABLE IF NOT EXISTS `TEST` (X   INT(16))
etc....

Of course &param is what I would have used in Oracle environment.

Thanks

Updates:

Forgot to mention that I am using a windows environment for now. I have created a batch script to call the mysql script. The easiest way I thought would be to pass to mysql 2 command: 1) use the schema I have as parameter and then call the script which will create the table regardless of the schema. Unfortunately mysql seems to understand that I want to connect to the schema X, but doesn't want to call the script.

REM param is the schema and mainsql is the script
SET param="%1"
SET mainsql="script.sql"

echo %param%
echo %mainsql%

mysql -u <user> --password=<psw>  %param% "source %mainsql%;"

1条回答
男人必须洒脱
2楼-- · 2019-05-06 21:20

As far as I know you can't directly pass variables in to a MySQL script. The best you can do is set user variables in a wrapper shell script. Something like:

passed_var1=$1
passed_var2=$2
mainsql=script.sql

mysql $(usual_parameters) -e "set @user_var1=$passed_var1; set @user_var2=$passed_var2; source $mainsql"

Adjust for actual use, of course.

查看更多
登录 后发表回答