I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:
mysql> source script.sql
How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.
I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.
Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
Like this:
set @department := 'Engineering';
Then, reference @department
wherever you need to in script.sql:
update employee set salary = salary + 10000 where department = @department;
#!/bin/bash #verify the passed params echo 1 cmd arg : $1 echo 2 cmd arg : $2 export db=$1 export tbl=$2 #set the params ... Note the quotes ( needed for non-numeric values ) mysql -uroot -pMySecretPaassword \ -e "set @db='${db}';set @tbl='${tbl}';source run.sql ;" ; #usage: bash run.sh my_db my_table # #eof file: run.sh --file:run.sql SET @query = CONCAT('Select * FROM ', @db , '.' , @tbl ) ; SELECT 'RUNNING THE FOLLOWING query : ' , @query ; PREPARE stmt FROM @query; EXECUTE stmt; DEALLOCATE PREPARE stmt; --eof file: run.sql
you can re-use the whole concept from from the following project
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With