How do I pass a variable to a mysql script?
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