Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Use environment variables in script

Is it possible to make a sql script use a variable defined externally?

E.g. I have the following script:

UPDATE mytable
SET    valid = 0
WHERE  valid = 1

which I have to run through mysql command line several times, each with a different table name.

I would like something like:

SET table_name=foo
mysql -uuser -ppassword < myscript.sql

is it possible?

like image 259
Don Avatar asked Apr 22 '11 12:04

Don


People also ask

What is the difference between environment variables and options in MySQL?

Options on the command line take precedence over values specified in option files and environment variables, and values in option files take precedence over values in environment variables. In many cases, it is preferable to use an option file instead of environment variables to modify the behavior of MySQL.

How to pass a variable to a MySQL script?

You can pass a variable to a MySQL script using session variable. First you need to set a session variable using SET command. After that you need to pass that variable to a MySQL script. The syntax is as follows − First Step: Use of Set command. Second Step: Pass a variable to a MySQL script.

How to set session variables in a MySQL script?

First you need to set a session variable using SET command. After that you need to pass that variable to a MySQL script. The syntax is as follows − First Step: Use of Set command.

What are system variables in MySQL?

Declare System Variables in MySQL There is a third type of variable called system variables used to store values that affect individual client connections (SESSION variables) or affect the entire server operation (GLOBAL variables). System variables are usually set at server startup.


1 Answers

Skirting around the environment variables, why not:

sed 's/mytable/foo/' myscript.sql | mysql -uuser -ppassword
like image 56
VoteyDisciple Avatar answered Oct 08 '22 10:10

VoteyDisciple